简体   繁体   中英

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.

Just plain trying to assign a to i gives me this error message: 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

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. To make it work you need to tell compiler that a is actually an 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. 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 .

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 .

There's a gradient of generality and usefulness. On one extreme is 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 . If you have a parameter that expects an Int , only one type of value is allowed: 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? / as! into a more restricting (less general) type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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