Can I cast a metaclass object to a protocol type in Swift?

拥有回忆 提交于 2019-12-04 03:40:57

As of Xcode 7 beta 2 and Swift 2 it has been fixed. You can now write:

for type in types {
    if let fooType = type as? Foo.Type {
        // in Swift 2 you have to explicitly call the initializer of metatypes
        let obj = fooType.init(foo: "special snowflake string")
    }
}

Or if you only want type as type Foo.Type you can use for case

for case let type as Foo.Type in types {
    let obj = type.init(foo: "special snowflake string")
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!