首页 > 解决方案 > 如何访问存储在“Any”类型变量中的值

问题描述

我可以很容易地将值存储在类型变量中Any,但我不知道如何访问它。

只是简单地尝试分配ai我这个错误信息:error: cannot convert value of type 'Any' to specified type 'Int'

并尝试投射它给我这个错误信息: error: protocol type 'Any' cannot conform to 'BinaryInteger' because only concrete types can conform to protocols

let a: Any = 1

//this doesn't work
let i: Int = a

//this doesn't work
let i: Int = Int(a)

标签: swiftpolymorphismswift5

解决方案


它不起作用,因为 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
}

推荐阅读