我正在尝试将 Swift 书中的 Matrix 示例移植为通用的。
这是我到目前为止得到的:
struct Matrix<T> {
let rows: Int, columns: Int
var grid: T[]
init(rows: Int, columns: Int, repeatedValue: T) {
self.rows = rows
self.columns = columns
grid = Array(count: rows * columns, repeatedValue: repeatedValue)
}
func indexIsValidForRow(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
subscript(row: Int, column: Int) -> T {
get {
assert(indexIsValidForRow(row, column: column), "Index out of range")
return grid[(row * columns) + column]
}
set {
assert(indexIsValidForRow(row, column: column), "Index out of range")
grid[(row * columns) + column] = newValue
}
}
}
请注意,我必须将 repeatedValue: T
传递给构造函数。
在 C# 中,我会使用 default(T)
,对于数字,它是 0
,对于 bool 值,它是 false
,而 null
对于引用类型。我知道 Swift 不允许在非可选类型上使用 nil
但我仍然很好奇是否传递显式参数是唯一的方法,或者我是否有 some相当于 default(T)
。
最佳答案
没有。 Swift 强制您指定默认值,就像您处理变量和字段一样。 Swift 具有默认值概念的唯一情况是可选类型,它是 nil
(Optional.None
)。
关于swift - Swift 中没有 default(T) 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24136604/