gpt4 book ai didi

json - 将 AnyObject 转换为 Double

转载 作者:可可西里 更新时间:2023-11-01 00:16:55 25 4
gpt4 key购买 nike

我正在尝试使用以下代码解析 JSON:

    func ltchandler(response: NSURLResponse!, data : NSData!, error : NSError!) { //Is passed the results of a NSURLRequest

if ((error) != nil) {
//Error Handling Stuff
} else {
if (NSString(data:data, encoding:NSUTF8StringEncoding) == "") {

//Error Handling Stuff
} else {
var data = NSData(data: data);

// Define JSON string
var JSONString = "\(data)"



// Get NSData using string
if let JSONData = JSONString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {


// Parse JSONData into JSON object
var parsingError: NSError?
if let JSONObject = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &parsingError) as? [String: AnyObject] {


// If the parsing was successful grab the rate object
var rateObject: Double! = JSONObject["price"]?.doubleValue

// Make sure the rate object is the expected type
if let rate = rateObject as? Double! { // THIS IS NOT WORKING!!!
//Do stuff with data
} else {
println("Parsing Issue")

}
}
}

}
}



}

标记为 THIS NOT WORKING!!! 的行未被调用。

据我所知,它不能将 rateObject 转换为 double - 为什么不呢?它没有显示任何错误。

澄清一下,预期的行为是从 JSON 对象创建 double 值。

最佳答案

为了严格回答您的问题,您是否尝试过打印 rateObject。另外,为什么要在有问题的行中强制转换为 Double! 而不是 Double

我个人几乎在所有情况下都不使用 !。您最好使用非可选值或适当的可选值。

在相关部分我会写:

// Make sure the rate object is the expected type
if let rate = JSONObject["price"]?.doubleValue {
//Do stuff with rate
} else {
print("Parsing Issue")
}

当然,如果 JSONObject["price"] 不是带有 doubleValue 方法的东西,或者该方法返回 nil,您最终会得到使用 nil 和 else 情况。

关于json - 将 AnyObject 转换为 Double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28344425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com