1.Keypath
class User {
var name: String = "张三"
var age: Int = 9
}
let user1 = User()
user1.name = "李四"
user1.age = 10
let name = user1[keyPath: \User.name]
let age = user1[keyPath: \User.age]
print(name,age) // 李四 10
2. 类与协议的组合类型
protocol Shakeable {
func shake()
}
extension UIButton: Shakeable {
func shake() {
print("shake~~~~~",self.tag)
}
}
override func viewDidLoad() {
super.viewDidLoad()
let titles = ["按钮1", "按钮2", "按钮3"]
let colors = [UIColor.red, UIColor.blue, UIColor.orange]
let buttons = zip(0..., titles).map { (i, title) -> UIButton in
let button = UIButton(type: .system)
button.frame = CGRect(x: i * 100, y: 200, width: 80, height: 80)
button.setTitle(title, for:.normal)
button.tag = i
self.view.addSubview(button)
return button
}
zip(buttons, colors).forEach({
$0.0.backgroundColor = $0.1
})
shakeEm(controls: buttons)
}
func shakeEm(controls: [UIControl & Shakeable]) {
for control in controls where control.isEnabled {
control.shake()
}
}
打印结果
shake~~~~~ 0
shake~~~~~ 1
shake~~~~~ 2