How to make extension for multiple classes Swift

前端 未结 2 2060
天涯浪人
天涯浪人 2021-02-05 02:36

I have an extension:

extension UILabel {
    func animateHidden(flag: Bool) {
        self.hidden = flag
    }
}

I need to make the same one fo

2条回答
  •  一个人的身影
    2021-02-05 02:43

    You could make a protocol and extend it.

    Something like:

    protocol Animations {
        func animateHidden(flag: Bool)
    }
    
    extension Animations {
        func animateHidden(flag: Bool) {
            // some code
        }
    }
    
    extension UILabel: Animations {}
    
    extension UIImageView: Animations {}
    

    Your method will be available for the extended classes:

    let l = UILabel()
    l.animateHidden(false)
    
    let i = UIImageView()
    i.animateHidden(false)
    

    In a comment, you've asked: "in this case how to call self for UILabel and UIImageView in animateHidden function?". You do that by constraining the extension.

    Example with a where clause:

    extension Animations where Self: UIView {
        func animateHidden(flag: Bool) {
            self.hidden = flag
        }
    }
    

    Thanks to @Knight0fDragon for his excellent comment about the where clause.

提交回复
热议问题