How to use a protocol with optional class methods in an extension with generic in Swift?

怎甘沉沦 提交于 2019-12-06 00:23:33

It looks like you've found a (fairly obscure) bug in the Swift compiler that's causing it to crash. Here's a reproduction that's all you need in a single file to crash swiftc:

import Foundation
@objc protocol P { optional class func f() }
func f<T: P>(t: T) { T.self.f?() }

(you don't need to call f for it to crash)

You should probably file a radar since the compiler crashing is never expected behavior no matter what your code.

If you tried to do this without the optional, it'll work (and you can even ditch the self). My guess is the implementation of generics doesn't currently account for the possibility of optional class-level functions.

You can do it without generics like this:

func f(p: MyProtocol) {
    (p as AnyObject).dynamicType.foo?()
}

(there may even be a better way but I can't spot it).

You need the AnyObject cast because if you try to call .dynamicType.foo?() on p directly you get "accessing members of protocol type value 'MyProtocol.Type' is unimplemented". I wouldn't be surprised if the crash of the generic version is related to this.

I'd also say that its worth asking yourself whether you really need a protocol with optional methods (especially class-level ones) and whether there's a way to do what you want entirely statically using generics (as you're already semi-doing).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!