Swift 编程:对象类型声明与特性深度解析
1. 静态代码中的 self 使用
在静态或类代码中, self 代表类型本身。不过在某些情况下,使用 self 会引发编译器错误。例如:
struct Greeting {
static let friendly = "hello there"
static let hostile = "go away"
static let ambivalent = Greeting.friendly + " but " + Greeting.hostile
}
这里不能直接用 self ,为避免编译器报错,使用类型名来明确 friendly 和 hostile 的状态。
若将 ambivalent 写成计算属性,就可以使用 self :
struct Greeting {
static let friendly = "hello there"
static let hostile = "go away"
static var ambivalent : String {
return self.friendly + " but " + self.hostile
}
}
Swift对象类型与特性解析
超级会员免费看
订阅专栏 解锁全文
98

被折叠的 条评论
为什么被折叠?



