swift - 如何访问存储在“Any”类型变量中的值
问题描述
我可以很容易地将值存储在类型变量中Any
,但我不知道如何访问它。
只是简单地尝试分配a
给i
我这个错误信息: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)
解决方案
它不起作用,因为 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
}
推荐阅读
- python - xml文件的每次迭代的新列表
- docker - 如何在 k8s 中等待其他容器完成执行?
- python-3.x - 用换行符打印长字符串的 Python 指令代码
- python - Python编写函数将大写引入布尔值
- javascript - 使用 tensorflow-js 在网络摄像头上进行对象检测
- javascript - 什么允许在 index[some string] 和基础行为处分配数组
- python - 如何根据熊猫中的列条件选择多行作为一个组
- xamarin.forms - 可以通过 FFImageLoading CachedImage 从平台资产文件夹加载 SKBitmap?
- r - 使用 googlelanguageR 将语音转文本生成 NULL 成绩单
- node.js - 如何使用 Express 将获取请求重定向到静态图像资产