在Swift中检查Double时总是找到nil

时间:2019-04-08 19:49:32

标签: swift

我有以下代码:

p + geom_segment(aes(x = 2, y = -0.5, xend = 4, yend = -0.5 )) +
        geom_segment(aes(x = 5, y = -0.5, xend = 7, yend = -0.5)) 

我这样做是因为我有可能从该数据中接收null。我的问题是,我总是在第一个打印中收到一个双精度值(当项返回一个值时),而在第二个打印中则为nil。是否因为itemObject.value(forKey:“ tons”)的值是可选的?

我试图强制解开该值,但是当它为null时,它会中断。我需要它可以为空,但是我在以各种有记载的方式进行处理时都遇到了麻烦。我知道有一个非常简单的答案,但是我还没有找到。任何帮助将不胜感激。

相关的JSON:

//create an NSURL
    let url = NSURL(string: self.urlString)

    //fetch the data from the url
    URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in

        //If the retrieved information is a JSON Object, and can be treated as an NSArray...
        if let jsonObj = (try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSObject) {

            let data = jsonObj.value(forKey: "pendingloads") as! NSArray

            for item in data {

                if let itemObject = item as? NSObject {

                    print("Tons value1: \(itemObject.value(forKey: "tons")!)")
                    let tons = itemObject.value(forKey: "tons") as? Double ?? nil
                    print("Tons value2: \(String(describing: tons))")

为了改进,下面是更新的代码:

}   
   "pendingloads": [
   {
      "comment": "Test Comment",
      "hauler": "Test Hauler",
      "logs": [
          {
             "coords": "(25.123456, -120.123456)",
             "type": "auth",
             "timestamp": "2019-04-04 10:52:1554393131",
             "device_id": "DEVICE-ID-DEVICE-ID-DEVICEID"
           },
           {
             "coords": "(25.123456, -120.123456)",
             "type": "update",
             "timestamp": "2019-04-08 13:38:1554748736",
             "device_id": "DEVICE-ID-DEVICE-ID-DEVICEID"
            }
       ],
       "tons": "12.800",
       "load_id": 23,
       "requires_correction": false,
       "trailer_drop": true,
       "gross": "25600.000",
       "contract_id": 3679,
       "scaleticket": "2134098",
       "destination": "TEST DESTINATION",
       "sale_id": 3961,
       "tare": "0.000",
       "net": "25600.000",
       "cull": "157.000",
       "product": "Test Product",
       "operator_id": 2674,
       "hauler_id": 617,
       "timestamp": "2019-04-08 18:38:1554766680",
       "driver": "Terry",
       "ticket": 250,
       "product_id": 3172,
       "sale": "Test Sale",
       "trailer": "013724589"
     }
   ]
 }

1 个答案:

答案 0 :(得分:1)

您可以尝试

struct Root: Codable {
    let pendingloads: [Pendingload]
}

struct Pendingload: Codable {
    let comment, hauler: String
    let logs: [Log]
    let tons: String
    let loadId: Int
    let requiresCorrection, trailerDrop: Bool
    let gross: String
    let contractId: Int
    let scaleticket, destination: String
    let saleId: Int
    let tare, net, cull, product: String
    let operatorId, haulerId: Int
    let timestamp, driver: String
    let ticket, productId: Int
    let sale, trailer: String

}

struct Log: Codable {
    let coords, type, timestamp, deviceId: String 
}

 let url = URL(string: self.urlString)! 

 URLSession.shared.dataTask(with:url) { (data, response, error) in 
    guard let data = data else { return }
    do {
        let res = JSONDecoder()
        res.keyDecodingStrategy = .convertFromSnakeCase
        let ss = try res.decode(Root.self, from:data)
        print(ss)
    }
    catch {
        print(error)
    }

}.resume()