Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Any to Int in Swift

Tags:

swift

I get an error when declaring i

var users =  Array<Dictionary<String,Any>>()
users.append(["Name":"user1","Age":20])
var i:Int = Int(users[0]["Age"])

How to get the int value?

like image 316
ielyamani Avatar asked Jun 06 '14 23:06

ielyamani


People also ask

How do I convert text to INT in Swift?

Using Int initializer Swift provides the function of integer initializers using which we can convert a string into an Int type. To handle non-numeric strings, we can use nil coalescing using which the integer initializer returns an optional integer.


Video Answer


2 Answers

var i = users[0]["Age"] as Int

As GoZoner points out, if you don't know that the downcast will succeed, use:

var i = users[0]["Age"] as? Int

The result will be nil if it fails

like image 91
Joseph Mark Avatar answered Oct 19 '22 17:10

Joseph Mark


Swift 4 answer :

if let str = users[0]["Age"] as? String, let i = Int(str) {
  // do what you want with i
}
like image 25
ergunkocak Avatar answered Oct 19 '22 18:10

ergunkocak