且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Swift 2协议扩展和对Objective-C类型的一致性

更新时间:2022-05-31 22:14:08

问题是尝试混合使用Objective-C和Swift功能.这段纯Swift代码可以很好地编译(请注意,我已从故事中删除了NSManagedObject,因为它与问题无关):

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 [:]
    }
}

那是因为Swift知道什么是协议扩展.但是,Objective-C不会!因此,只要您说出@objc protocol,便会将协议移至Objective-C世界,并且协议扩展无效-因此Model不符合,因为它没有updateSyncState实现.

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.