How to write a generic apply() function in Swift?

后端 未结 4 1429
你的背包
你的背包 2020-12-16 11:45

Is there any way to get the following working in Swift 3?

 let button = UIButton().apply {
        $0.setImage(UIImage(named: \"UserLocation\"), for: .normal         


        
4条回答
  •  执念已碎
    2020-12-16 12:37

    There's a very good and simple Cocoapods library available called Then that does exactly that. Only that it uses then instead of apply. Simply import Then and then you can do as the OP asked for:

    import Then
    
    myObject.then {
        $0.objectMethod()
    }
    
    let label = UILabel().then {
        $0.color = ...
    }
    

    Here's how the protocol is implemented: https://github.com/devxoul/Then/blob/master/Sources/Then/Then.swift

    extension Then where Self: Any {
        public func then(_ block: (Self) throws -> Void) rethrows -> Self {
            try block(self)
            return self
        }
    

提交回复
热议问题