Swift 添加下标 subscript
xxxixxxx

关键子 subscript

参数和返回值可以是任意类型(inout输入输出除外)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
struct People {
var name = "", age = 0

// 给实例添加下标
subscript(n: String) -> Int {
get {
return age
}
set {
age = newValue
}
}

// 给结构体添加下标
static subscript(name: String, age: Int) -> People {
People(name: name, age: age)
}
}

var a = People(name: "哈哈哈", age: 18)
print(a["哈哈哈"])//18
a["哈哈哈"] = 20
print(a["哈哈哈"])//20
let p = People["哈喽", 20]
print(p)//People(name: "哈喽", age: 20)
  • Post title:Swift 添加下标 subscript
  • Post author:xxxixxxx
  • Create time:2020-11-23 00:00:00
  • Post link:https://xxxixxx.github.io/2020/11/23/100-Swift-添加下标-subscript/
  • Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.
 Comments