Chéyo
Chéyo

Reputation: 9367

Int in list with String is AnyObject?

What is wrong with this code?

How can I specify the list to be Strings and Numbers?

I am getting an error 'AnyObject is not convertible to 'Int'

var stringNum = ["name", 2]

var number:Int = stringNum[1]

Upvotes: 2

Views: 2077

Answers (2)

drewag
drewag

Reputation: 94713

The array is inferred to be of the type [AnyObject] and in swift, you must always explicitly downcast your variables.

You need to test if the value can be converted to an Int:

if let number : Int = stringNum[1] as? Int {
    // use number as Int
}

The as? operator will return nil if the value cannot be converted and the if block will not be run, otherwise it will return the value converted to Int and run the if block with number set to the Int value

Upvotes: 2

GoZoner
GoZoner

Reputation: 70135

If you are confident that elements in your array are typed as you expect then simply

 var number:Int = stringNum[1] as Int

works. But, if you are unsure about the type consistency in your array elements then you'll need to confirm the types before assigning.

Upvotes: 1

Related Questions