Protocol extension in Swift 3 [duplicate]

。_饼干妹妹 提交于 2019-12-20 07:47:10

问题


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


来源:https://stackoverflow.com/questions/44063181/protocol-extension-in-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!