我可以很容易地将一个值存储在 Any
类型的变量中,但我不知道如何访问它。
只是简单地尝试将 a
分配给 i
给我这个错误消息:error: cannot convert value of type 'Any' to specified type 'Int'
尝试转换它给我这个错误信息:
错误:协议(protocol)类型“Any”不能符合“BinaryInteger”,因为只有具体类型才能符合协议(protocol)
let a: Any = 1
//this doesn't work
let i: Int = a
//this doesn't work
let i: Int = Int(a)
最佳答案
它不起作用,因为 Int 没有接受类型 Any 的初始化器。为了让它工作,你需要告诉编译器 a 实际上是一个 Int。你这样做是这样的:
let a: Any = 1
let i: Int = a as! Int
编辑: 如果您不确定 a 的类型,则应使用可选类型转换。有很多方法。
let i1: Int? = a as? Int // have Int? type
let i2: Int = a as? Int ?? 0 // if a is not Int, i2 will be defaulted to 0
guard let i3 = a as? Int else {
// what happens otherwise
}
关于swift - 如何访问存储在类型为 "Any"的变量中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57749494/