Swift 2 Protocol Extensions and Conformance for Objective-C Types

偶尔善良 提交于 2019-12-02 11:20:51

问题


I have a setup like this:

@interface Model: NSManagedObject
...
@end

And a Swift protocol like this:

@objc protocol Syncable {
    var uploadURL: String { get }
    var uploadParams: [String: AnyObject]? { get }
    func updateSyncState() throws
}

extension Syncable where Self: NSManagedObject {
    func updateSyncState() throws {
        ... /* default implementation */ ...
    }
}

In a new Swift file, I try to do this:

extension Model: Syncable {
    var uploadURL: String {
        return "a url"
    }
    var uploadParams: [String: AnyObject]? {
        return [:]
    }
}

I keep getting an error, with Xcode saying "type 'Model' does not conform to protocol 'Syncable'". Xcode also keeps suggesting that I put an @objc somewhere in my extension but it can't seem to figure out where it should go.

Is what I'm doing impossible? (It seems to work under simple conditions in a playground - but with my Objective-C class being written in Swift, obviously).

If it is impossible, help in understanding why would be appreciated.


回答1:


The problem is the attempt to mix Objective-C and Swift features. This pure Swift code compiles just fine (note that I've eliminated NSManagedObject from the story, as it has nothing to do with the issue):

class MyManagedObject {}

class Model: MyManagedObject {}

protocol Syncable {
    var uploadURL: String { get }
    var uploadParams: [String: AnyObject]? { get }
    func updateSyncState()
}

extension Syncable where Self: MyManagedObject {
    func updateSyncState() {
    }
}

extension Model: Syncable {
    var uploadURL: String {
        return "a url"
    }
    var uploadParams: [String: AnyObject]? {
        return [:]
    }
}

That's because Swift knows what a protocol extension is. But Objective-C doesn't! So as soon as you say @objc protocol you move the protocol into the Objective-C world, and the protocol extension has no effect - and thus Model doesn't conform, as it has no updateSyncState implementation.



来源:https://stackoverflow.com/questions/33978516/swift-2-protocol-extensions-and-conformance-for-objective-c-types

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