Search code examples
iosswiftswift-protocolsswift-extensions

Protocol extension in Swift 3


I want to have a default property of UIImageView, which would be isFlipped. I am able to do it by subclassing UIImageView and adding one property isFlipped. But I want to user protocol and extensions for this , but it is crashing after sometime. Below is my code. How can I use it in right way? Thanks

import Foundation
import UIKit

protocol FlipImage {
    var isFlipped: Bool { get set }
}

extension UIImageView:FlipImage{
    var isFlipped: Bool {
        get {
            return  self.isFlipped
        }
        set {
            self.isFlipped = newValue
        }
    }
}

Solution

  • As Martin R said you can't add stored properties to a class through class extensions. But you can use the objective C associated objects to do it via an extension

    private var key: Void?
    
    extension UIImageView {
        public var isFlipped: Bool? {
            get {
                return objc_getAssociatedObject(self, &key) as? Bool
            }
    
            set {
                objc_setAssociatedObject(self,
                                         &key, newValue,
                                         .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            }
        }
    }