简体   繁体   English

如何访问存储在“ Any”类型变量中的值

[英]How can I access values stored in a variable of type “Any”

I can store a value in a variable of type Any quite easily, but I can't figure out how to access it. 我可以很容易地将值存储在Any类型的变量中,但是我不知道如何访问它。

Just plain trying to assign a to i gives me this error message: error: cannot convert value of type 'Any' to specified type 'Int' 只是简单的尝试指派ai给我这个错误信息: error: cannot convert value of type 'Any' to specified type 'Int'

And trying to cast it gives me this error message: 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给我以下错误消息: 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)

It doesn't work because Int doesn't have an initializer that accepts type Any. 它不起作用,因为Int没有接受类型为Any的初始化程序。 To make it work you need to tell compiler that a is actually an Int. 为了使其工作,您需要告诉编译器a实际上是一个Int。 You do this like this: 您可以这样操作:

let a: Any = 1
let i: Int = a as! Int

Edit: If you are not sure about type of a, you should use optional casting. 编辑:如果不确定a的类型,则应使用可选的强制转换。 There are many approaches. 有很多方法。

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
}

You can access it. 您可以访问它。 It's just a . 只是a

But you can't do much beyond that. 但除此之外,您无能为力。 Aside from a handful of actually universal functions ( print , dump , etc.), there's really not much that you can do with an Any . 除了少数实际通用的功能( printdump等)之外,使用Any确实可以做很多事情。

There's a gradient of generality and usefulness. 普遍性和有用性之间存在梯度。 On one extreme is Any . 一个极端是Any It's nearly useless. 这几乎没有用。 It doesn't require anything of its conforming types. 它不需要任何符合标准的类型。 But as a result, it's incredibly general. 但是结果是,它是如此的普遍。 Literally all types conform to it. 从字面上看,所有类型都符合它。

On the other extreme is a concrete type like Int . 另一个极端是像Int这样的具体类型。 If you have a parameter that expects an Int , only one type of value is allowed: Int . 如果您有一个期望为Int的参数,则仅允许使用一种类型的值: Int But this specificity buys you utility. 但是这种特殊性会为您带来实用性。 You know that this value supports being added, multiplied, converted to string, etc. 您知道此值支持加,乘,转换为字符串等。

The only way to do anything useful with Any is to down-cast it with as / as? Any执行任何有用的唯一方法是使用as / as?向下转换它as? / as! / as! into a more restricting (less general) type. 变成更具限制性(较不通用)的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM