简体   繁体   中英

How to convert string in JSON to int 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)

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
}

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

I'm not sure about your question, but say you have a dictionary (Where it was JSON or not) You can do this:

var dict: [String : String]
dict = ["key1" : "123"]

var x : Int
x = dict["key1"].toInt()
println(x)

Just in case someone's still looking for an updated answer, here's the Swift 5+ version:

let jsonDict = ["key": "123"];
// Validation
guard let value = Int(jsonDict["key"]) else {
    print("Error! Unexpected value.")
    return
}
print("Integer conversion successful: \(value)")

// Prints "Integer conversion successful: 123"

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