gpt4 book ai didi

swift - 如何检查 Any 值是否确认通用协议(protocol),例如整数类型

转载 作者:搜寻专家 更新时间:2023-10-31 19:35:23 25 4
gpt4 key购买 nike

是否可以动态检查一个值来确认通用协议(protocol)?

我想做这样的事情:

import func Darwin.atoll
func anyToInt(a: Any) -> IntMax {
if let v = a as? IntegerType { // error!!
return v.toIntMax()

} else {
return atoll("\(a)")
}
}

这会导致编译错误并显示消息“错误:协议(protocol)‘IntegerType’只能用作通用约束...”。

如果我使用了正确的静态类型,我会通过类型参数约束使用重载:

func anyToInt<T where T: IntegerType>(a: T) -> IntMax {
return a.toIntMax()
}
func anyToInt<T>(a: T) -> IntMax {
return atoll("\(a)")
}

不幸的是,在我的例子中,没有方法可以使用静态类型来代替 Any。

最佳答案

你不能,有几个原因:

首先,你can’t cast the contents of an Any to a protocol Any 可能支持。您只能获取包含的显式类型:

let i = 1
i as Printable // works

let a: Any = i
a as? Printable // doesn’t work
let p = a as Int as Printable // works
// or, if you don’t want to crash if a isn’t an Int
let p = (a as? Int).map { $0 as Printable }
// (is there a cleaner syntax than this?)

其次,您无法实例化具有关联类型的协议(protocol)。您只能将它们用作通用约束。 Printable 的示例之所以有效,是因为它没有关联的类型。参见 this answer解释原因。因此,即使转换 Any 可以在协议(protocol)上工作,您也无法将其转换为 IntegerType

但是你确定你必须在这里使用 Any 吗? Any 除非别无选择,否则最好避免使用。也许您可以将泛型进一步推向管道?

关于swift - 如何检查 Any 值是否确认通用协议(protocol),例如整数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27737494/

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