Failing cast in Swift from Any? to protocol

前端 未结 4 1879
执念已碎
执念已碎 2020-11-27 22:23

FYI: Swift bug raised here: https://bugs.swift.org/browse/SR-3871


I\'m having an odd problem where a cast isn\'t working, but the console shows it as the corre

4条回答
  •  爱一瞬间的悲伤
    2020-11-27 22:51

    The problem is that the sender must pass through the Objective-C world, but Objective-C is unaware of this protocol / struct relationship, since both Swift protocols and Swift structs are invisible to it. Instead of a struct, use a class:

    protocol MyProtocol {}
    class MyClass: MyProtocol { }
    func make() -> MyProtocol { return MyClass() }
    

    Now everything works as you expect, because the sender can live and breathe coherently in the Objective-C world.

提交回复
热议问题