Danny Danny - 1 year ago 168
Swift Question

How to make extension for multiple classes Swift

I have an extension:

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

I need to make the same one for
but I don't want to copy that whole code. Is it possible to make an extension for multiple classes?


Answer Source

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 classes adopting the extended protocol:

let l = UILabel()

let i = UIImageView()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download