//: Playground - noun: a place where people can play
import UIKit
/************ 下标 ****************/
// 类, 结构体 , 枚举 可以定义下标
// 下标可以传入 多个不同类型的参数, 返回一个任意类型的数据
// 下标中 可以使用 get 和 set 模式(read-write 和 readOnly)
//subscript(index: Int) -> Int {
// get {
// // return an appropriate subscript value here
// return 3
// }
// set(newValue) {
// // perform a suitable setting action here
// }
//}
//subscript(index: Int) -> Int {
// // return an appropriate subscript value here
// return 3
//}
struct TimesTable {
let multiplier: Int
subscript(index: Int) -> Int {
return multiplier * index
}
}
let threeTimesTable = TimesTable(multiplier: 3)
print("six times three is \(threeTimesTable[6])")
// Prints "six times three is 18”
// 在集合中使用下标
var numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
numberOfLegs["bird"] = 2
//下面有个矩阵的例子
struct Matrix{
let rows: Int, columns: Int
var grid: [Double]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
grid = Array(repeating: 0.0, count: rows * columns)
}
func indexIsValid(row: Int, column: Int) -> Bool{
return row >= 0 && row < rows && column >= 0 && column < columns
}
subscript(row: Int, column: Int) -> Double{
get {
assert(indexIsValid(row: row, column: column), "Index out of range")
return grid[(row * column) + column]
}
set {
assert(indexIsValid(row: row, column: column), "Index out of range")
grid[(row * column) + column] = newValue
}
}
}
var matrix = Matrix(rows: 2, columns: 2)
matrix[0,1] = 1.5
matrix[1,0] = 3.2
print(matrix[0,1])
print(matrix[1,0])
swift - subscrip 下标
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
相关阅读更多精彩内容
- 最近升级Xcode8后运行提示Swift版本错误,具体错误如下: “Use Legacy Swift Langua...
- 本章将会介绍 下标语法下标用法下标选项定义一个基类子类生成重写防止重写 下标 下标可以定义在类、结构体和枚举中,是...
- 1. 类 Swift中的结构体和类非常相似,但是又有不同之处类是具有相同属性、方法的抽象格式: 类没有逐一构造器 ...