Swift 2 Protocol Extensions and Conformance for Ob

2019-03-02 07:01发布

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条回答
在下西门庆
2楼-- · 2019-03-02 07:17

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.

查看更多
登录 后发表回答