• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

1.swift的keypath、类和协议的组合类型

武飞扬头像
_Invoker
帮助1

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

学习课件

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgabbfb
系列文章
更多 icon
同类精品
更多 icon
继续加载