第一部分是 UILabel 和 UIButton 都有一个 text 属性。
protocol TextProtocol: class {
var text: String? { get set }
}
extension UIButton: TextProtocol {
var text: String? {
get {
return self.titleLabel?.text
} set {
self.titleLabel?.text = newValue
}
}
}
extension UILabel: TextProtocol {}
第二部分以第一部分为基础,确保 UILabel 和 UIButton 都具有animate(text:duration:) 函数。
protocol AnimatableTextProtocol: TextProtocol where Self: UIView {}
extension AnimatableTextProtocol {
func animate(text: String, duration: TimeInterval) {
UIView.transition(with: self, duration: duration, options: [], animations: {
self.text = text
})
}
}
extension UILabel: AnimatableTextProtocol {}
extension UIButton: AnimatableTextProtocol {}
注意:如果您从 TextProtocol 中删除 class,则 animate 函数会将其 self 视为不可变的,因为值类型也可以从协议继承。通过 class 部分,AnimatableTextProtocol 知道它可以与使 self 可变的引用类型一起工作,因此文本属性可分配给。
func yeah(button: UIButton, label: UILabel) {
button.text = "hello"
label.text = "world"
button.animate(text: "hello2", duration: 0.5)
label.animate(text: "world", duration: 1.5)
}