我有一个教程,我正在从中学习 Swift 和有关下标选项的内容。以下是有关此主题的文档示例的简单代码。
struct Matrix {
let rows: Int, columns: Int
var print: [Double]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
print = Array(count: rows * columns, repeatedValue: 0.0)
}
subscript(row: Int, column: Int) -> Double {
get {
return print[(row * columns) + column]
}
set {
print[(row * columns) + column] = newValue
}
}
}
var mat = Matrix(rows: 3, columns: 3)
mat[0,0] = 1.0
mat[0,1] = 2.0
mat[1,0] = 3.0
mat[1,1] = 5.0
println("\(mat[0,0])")
println("\(mat[0,1])")
println("\(mat[1,0])")
println("\(mat[1,1])")
任何人都可以解释一下这里发生了什么吗?我无法从这个例子中看出下标选项。可能会有很多像我这样的人。提前致谢。
最佳答案
Subscripts enable you to query instances of a type by writing one or more values in square brackets after the instance name. Their syntax is similar to both instance method syntax and computed property syntax. You write subscript definitions with the subscript keyword, and specify one or more input parameters and a return type, in the same way as instance methods. Unlike instance methods, subscripts can be read-write or read-only. This behavior is communicated by a getter and setter in the same way as for computed properties
我认为苹果 description很好。
如果您喜欢 Ray Wenderlich - 请参阅 here .
关于ios - iOS Swift 中的下标选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33995658/