ios - Swift 同时将对象转换为类型和协议(protocol)

标签 ios swift core-data swift3 swift-protocols

如何将给定对象转换为类型和协议(protocol),以便调用一些定义为扩展的方法

例如:

extension Identifiable where Self: NSManagedObject, Self: JsonParseDescriptor {
    func someMethod() { }
}

现在我有一个从核心数据中检索到的对象,我想将其转换为上述协议(protocol),以便在其上调用 someMethod。我可以使用 protocol<Identifiable, JsonParseDescriptor> 转换为协议(protocol),但我怎样才能在其中包含 NSManagedObejct 类型呢?

谢谢

最佳答案

Swift 4 开始,现在可以直接进行上述转换而无需棘手的解决方法。该任务的完成方式与我们进行协议(protocol)组合的方式类似:

var myVar = otherVar as! (Type & Protocol)

不再需要扩展和桥接协议(protocol)。

关于ios - Swift 同时将对象转换为类型和协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38979099/

相关文章:

swift - 如何在没有强引用循环的情况下将对象生命周期组合在一起?

ios - RxSwift 的结构 View 模型

ios - 核心数据 : Timeout adding persistent store on application launch

ios - 多个UIManagedDocument用于读写

ios - Swift:CoreData – ManagedObjectContext-错误

iphone - 确定用户是否拒绝了 CoreLocation 权限

iphone - 从未调用过 LocationManager 的 didEnterRegion

ios - 织物/Crashlytics : 'ANSCompatibility.h' file not found

ios - 在 Swift 中通过 TCP 发送消息

ios - 模型、 View 和 Controller 之间的连接