简体   繁体   中英

Swift 2 Protocol Extensions and Conformance for Objective-C Types

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM