2015-02-05 66 views
2

我想用下面的代码来解析JSON:铸造AnyObject到双

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 IS NOT WORKING!!!不会被调用。

从我可以告诉,它不能将rateObject作为一个双 - 为什么不?它没有显示任何错误。

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

回答

6

要严格回答您的问题,您是否尝试过打印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你将结束零和其他情况下上当受骗。

+1

感谢罗布,答案改善。 – 2015-02-05 14:15:31

+0

谢谢,它工作 – MShah 2016-07-26 11:59:34

1

代码为我工作,试试这个代码:

// if the value equals nil or any String, the instruction abort the if 
// SWIFT 2.0 in xcode beta 5 
if let rate = Double((JSONObject["price"] as? String)!){ 
    // insert you code here 
} else { 
    print("error message") 
}