考虑
extension UIView {
static var Trick: UIIView {
let v = UIView()
v.backgroundColor = .yellow
return v
}
}
因此
addSubview(UIView.Trick)
等等。
但是
private lazy var yellowLabel: UILabel = {
let v = UILabel.Typical
v.font = U.systemFont(ofSize: 200)
return v
}()
当然是错误的。有没有办法......
extension V where V is one of the UIView types {
static var Trick: V {
let v = " V "()
v.backgroundColor = .yellow
return v
}
}
有办法吗?
类扩展中计算属性的类型可以是
Self
来指定调用该属性的具体类型。另外 Self()
创建该具体类型的实例:
extension UIView {
static var Trick: Self {
let v = Self()
v.backgroundColor = .yellow
return v
}
}
现在
private lazy var yellowLabel: UILabel = {
let v = UILabel.Trick // <-- Type is UILabel !
v.font = .systemFont(ofSize: 200)
return v
}()
编译并按预期工作。