![](/img/trans.png)
[英]In Swift 4, how can you get the string-representation of a data type stored in a variable of type 'Any'?
[英]How can I access values stored in a variable of type “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
给我以下错误消息: 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
}
您可以访问它。 只是a
。
但除此之外,您无能为力。 除了少数实际通用的功能( print
, dump
等)之外,使用Any
确实可以做很多事情。
普遍性和有用性之间存在梯度。 一个极端是Any
。 这几乎没有用。 它不需要任何符合标准的类型。 但是结果是,它是如此的普遍。 从字面上看,所有类型都符合它。
另一个极端是像Int
这样的具体类型。 如果您有一个期望为Int
的参数,则仅允许使用一种类型的值: Int
。 但是这种特殊性会为您带来实用性。 您知道此值支持加,乘,转换为字符串等。
对Any
执行任何有用的唯一方法是使用as
/ as?
向下转换它as?
/ as!
变成更具限制性(较不通用)的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.