Swift 中枚举、结构体和类的深入解析
1. 静态/类成员的类型名称推断
在 Swift 里,当需要某个枚举的实例时,你可以使用枚举用点号开头的简写形式。对于类型的静态/类成员,若其值为该类型的实例,也能采用同样的做法。例如, UIColor 有很多类属性会返回 UIColor 实例,所以在需要 UIColor 的地方可以省略 UIColor :
p.trackTintColor = .red // 替代 UIColor.red
再看下面这个结构体 Thing ,它有静态常量,其值为 Thing 实例:
struct Thing : RawRepresentable {
let rawValue : Int
static let one : Thing = Thing(rawValue:1)
static let two : Thing = Thing(rawValue:2)
}
当需要 Thing 实例时,就可以把 Thing.one 写成 .one :
let thing : Thing = .one
超级会员免费看
订阅专栏 解锁全文
2万+

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



