Protocol extension in Swift 3 [duplicate]

2019-03-06 19:27发布

问题:

This question already has an answer here:

  • EXC_BAD_ACCESS Using IBInspectable 1 answer

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
        }
    }
}

回答1:

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)
        }
    }
}