我试图从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
}
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,我必须传递repeatedValue: T给构造函数.
在C#中,我会使用的default(T)是0数字,false布尔值和null引用类型.我理解Swift不允许nil使用非可选类型,但我仍然很好奇,如果传递一个显式参数是唯一的方法,或者如果我有一些等效的那样default(T).
浮躁的“是”。您可以使用协议约束来指定通用类或函数只能与实现默认init函数(无参数)的类型一起使用的要求。这样的后果很可能是不好的(它不能像您认为的那样起作用),但是它与您的要求最接近,可能比“ NO”答案更接近。
对我来说,我个人认为这对开发新的泛型类很有帮助,然后最终我消除了约束并修复了其余问题。仅要求可以采用默认值的类型将限制通用数据类型的用途。
public protocol Defaultable
{
init()
}
struct Matrix<Type: Defaultable>
{
let rows: Int
let columns: Int
var grid: [Type]
init(rows: Int, columns: Int)
{
self.rows = rows
self.columns = columns
grid = Array(count: rows * columns, repeatedValue: Type() )
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3663 次 |
| 最近记录: |