gpt4 book ai didi

ios - 从 Any 向下转换为协议(protocol)

转载 作者:IT王子 更新时间:2023-10-29 05:21:23 26 4
gpt4 key购买 nike

我有以下代码。如何解决最后一行中的错误?

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 beta 发行说明说:

Dynamic casts (“as!", “as?" and “is”) now work with Swift protocol types, so long as they have no associated types.


您只能使用 检查协议(protocol)一致性(包括 isasas?) @objc 协议(protocol)Animal 不是 @objc

参见 Checking for Protocol Conformance Swift 书的一部分。

NOTE

You can check for protocol conformance only if your protocol is marked with the @objc attribute

关于ios - 从 Any 向下转换为协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24299635/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com