Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert AnyObject to an Int

Tags:

ios

swift

I'm trying to convert a anyObject to an Int. Here's my code:

println(currentObject[0])
println(_stdlib_getDemangledTypeName(currentObject[0]))

2
Swift.ImplicitlyUnwrappedOptional<Swift.AnyObject>

I'm trying to convert currentObject[0] to an Int. Here's what I tried:

let num: Int = currentObjec[0] as! Int

When I run the app, I get the following error:

Could not cast value of type '__NSCFString' (0x103c93c50) to 'NSNumber' (0x103535b88)

When I try this: currentObject[0].toInt()

I get an error saying

'AnyObject' does not have a member named 'toInt()'

The only way I'm able to make it work, is to do the following:

let numStr = currentObject[0] as! String
let num: Int = numStr.toInt()!

Is there a simpler way to do it? (Without having to first convert it to a String.)

like image 874
Jessica Avatar asked Jan 31 '26 01:01

Jessica


1 Answers

From the error message

Could not cast value of type '__NSCFString' (0x103c93c50) to 'NSNumber' (0x103535b88)

you can conclude that currentObject[0] is actually an NSString. In that case you can simply convert it with

let numStr = currentObject[0].integerValue

But note that this will crash if the array element is not an NSString.

like image 64
Martin R Avatar answered Feb 02 '26 16:02

Martin R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!