从Any转向协议 [英] Downcast from Any to a protocol
问题描述
我有以下代码。如何在最后一行解决错误?
I have the following code. How can I resolve the error in the last line?
protocol Animal {
func walk()
}
struct Cat: Animal {
func walk() {}
init() { }
}
var obj: Any = Cat()
var cat = obj as Animal // ERROR: cannot downcast from Any to unrelated type Animal
推荐答案
更新:这已在Swift 1.2+(Xcode 6.3+)中修复。 Xcode 6.3测试版发行说明:
Update: This has been fixed in Swift 1.2+ (Xcode 6.3+). The Xcode 6.3 beta release notes say:
动态演员表(as!,as?和is)现在可以使用Swift协议
类型,只要它们没有相关类型。
Dynamic casts ("as!", "as?" and "is") now work with Swift protocol types, so long as they have no associated types.
您只能检查协议一致性(包括
,为
,)为?
), @objc
协议。 Animal
不是 @objc
。
参见< a href =https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html#//apple_ref/doc/uid/TP40014097-CH25-XID_363>检查协议Swift书的一致性部分。
注意
NOTE
你只有当你的协议用@objc属性标记为
时才能检查协议一致性
You can check for protocol conformance only if your protocol is marked with the @objc attribute
这篇关于从Any转向协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!