gpt4 book ai didi

swift - Swift 中没有 default(T) 吗?

转载 作者:IT王子 更新时间:2023-10-29 05:17:25 25 4
gpt4 key购买 nike

我正在尝试将 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com