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

后端 未结 4 1437
你的背包
你的背包 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:17

    The HasApply protocol

    First of all lets define the HasApply protocol

    protocol HasApply { }
    

    and related extension

    extension HasApply {
        func apply(closure:(Self) -> ()) -> Self {
            closure(self)
            return self
        }
    }
    

    Next let make NSObject conform to HasApply.

    extension NSObject: HasApply { }
    

    That's it

    Let's test it

    let button = UIButton().apply {
        $0.titleLabel?.text = "Tap me"
    }
    
    print(button.titleLabel?.text) // Optional("Tap me")
    

    Considerations

    I wouldn't use NSObject (it's part of the Objective-C way of doing things and I assume it will be removed at some point in the future). I would prefer something like UIView instead.

    extension UIView: HasApply { }
    

提交回复
热议问题