简体   繁体   English

如何将 JSON 中的字符串转换为 int Swift

[英]How to convert string in JSON to int Swift

self.event?["start"].string

The output is = Optional("1423269000000")输出是 = Optional("1423269000000")

I want to get 1423269000000 as an Int我想得到 1423269000000 作为 Int

How can we achieve this?我们怎样才能做到这一点? I have tried many ways such NSString (but it changed the value)我已经尝试了很多方法,比如 NSString (但它改变了值)

Your value: 1,423,269,000,000 is bigger than max Int32 value: 2,147,483,647 .您的值: 1,423,269,000,000大于最大 Int32 值: 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:在 iPhone 4S 模拟器中,控制台输出为:

Max integer value is: 2147483647

And iPhone 6 simulator, the console output is:而iPhone 6模拟器,控制台输出是:

Max integer value is: 9223372036854775807

This information may help you.这些信息可能对您有所帮助。

But normally to convert Int to String:但通常将 Int 转换为 String:

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

And convert String to Int:并将 String 转换为 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输出: Integer conversion successful :123

So this way one can be sure if the conversion was successful or not , using Optional Binding所以,这样一个可以肯定,如果转换成功与否,使用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:我不确定你的问题,但说你有一本字典(它是 JSON 还是不是)你可以这样做:

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:以防万一有人仍在寻找更新的答案,这里是 Swift 5+ 版本:

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" // 打印“整数转换成功:123”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM