Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

ios - How to expose existing property on Obj-C class using an extension protocol in Swift

In Swift 1.1 we were able to have code like below compile and work where we exposed existing Objective-C properties through a protocol added by an extension. We also had a few where the property is handled by the extension.

@objc protocol Enableable: class {
    var enabled: Bool { get set }
}

let DisabledAlpha: CGFloat = 0.5
let EnabledAlpha: CGFloat = 1.0

extension UIButton: Enableable {}

extension UIImageView: Enableable {
    var enabled: Bool {
        get {
            return alpha > DisabledAlpha
        }
        set(enabled) {
            alpha = enabled ? EnabledAlpha : DisabledAlpha
        }
    }
}

When trying to compile this code using XCode 6.3 and Swift 1.2, we get the following error Type 'UIButton' does not conform to the protocol 'Enableable'. The UIImageView extension seems to compile fine.

Is there any way to expose these sort of existing properties from an Objective-C type or do we have to implement a proxying property with a different name?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The compiler error message

note: Objective-C method 'isEnabled' provided by getter for 'enabled' does not match the requirement's selector ('enabled')

gives a hint about the problem. The enabled property of UIButton is inherited from UIControl and in Objective-C declared as

@property(nonatomic, getter=isEnabled) BOOL enabled

Therefore the protocol method has to be

@objc protocol Enableable: class {
    var enabled: Bool { @objc(isEnabled) get set }
}

and the implementation (similarly as in Swift 1.2 error on Objective-C protocol using getter):

extension UIImageView: Enableable {
    var enabled: Bool {
        @objc(isEnabled) get {
            return alpha > DisabledAlpha
        }
        set(enabled) {
            alpha = enabled ? EnabledAlpha : DisabledAlpha
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...