Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string in JSON to int Swift

Tags:

swift

self.event?["start"].string

The output is = Optional("1423269000000")

I want to get 1423269000000 as an Int

How can we achieve this? I have tried many ways such NSString (but it changed the value)

like image 483
keatwei Avatar asked Sep 29 '22 20:09

keatwei


2 Answers

Your value: 1,423,269,000,000 is bigger than max Int32 value: 2,147,483,647. This may cause unexpected casting value. For more information, check this out: Numeric Types.

Try to run this code:

let maxIntegerValue = Int.max
println("Max integer value is: \(maxIntegerValue)")

In iPhone 4S simulator, the console output is:

Max integer value is: 2147483647

And iPhone 6 simulator, the console output is:

Max integer value is: 9223372036854775807

This information may help you.

But normally to convert Int to String:

let mInt : Int = 123
var mString = String(mInt)

And convert String to Int:

let mString : String = "123"
let mInt : Int? = mString.toInt()

if (mInt != null) {
    // converted String to Int
}
like image 66
Oguz Ozkeroglu Avatar answered Oct 06 '22 20:10

Oguz Ozkeroglu


Here is my safe way to do this using Optional Binding:

var json : [String:String];
json = ["key":"123"];


if var integerJson = json["key"]!.toInt(){
    println("Integer conversion successful : \(integerJson)")
}
else{
    println("Integer conversion failed")
}

Output: Integer conversion successful :123

So this way one can be sure if the conversion was successful or not, using Optional Binding

like image 23
Shreyash Mahajan Avatar answered Oct 06 '22 18:10

Shreyash Mahajan