2016-04-15 109 views
-1

所以我有一個函數從json文件中提取數據並解析它。它拋出了一個零錯誤,因爲一些json條目沒有「顏色」字段/數組。我如何解釋這一點,並把「錯誤」作爲沒有的文本。json缺少字段swift

func getData2(){ 

    let dataPath = NSBundle.mainBundle().pathForResource("cardata", ofType: "json") 
    if let JSONData = NSData(contentsOfFile: dataPath!) 
    { 
     do 
     { 
      if let dictionariesArray = try NSJSONSerialization.JSONObjectWithData(JSONData, options: NSJSONReadingOptions()) as? 
       [[String: AnyObject]] 
      { 
       for dictionary in dictionariesArray 
       { 
        let name = dictionary["name"] as! String 
        let type = dictionary["type"] as! String 
        let text = String(dictionary["text"]) 
        if let printingsArray = dictionary["colors"] as? [String] 
        { 
         let printingsString = String(printingsArray.joinWithSeparator("-")) 
         nameColor[name] = printingsString 
        } 
        nameType[name] = type 
        nameText[name] = text 
       } 
      } 

     } 
     catch 
     { 
      print("Could not parse file at") 
     } 
    } 

    struct Card { 
     let name: String 
     let type: String 
     let colorr: String 
     let textt: String 

     init(name: String, type: String, textt: String, colorr:String) { 
      self.name = name 
      self.type = type 
      self.textt = textt 
      self.colorr = colorr 

     } 
    } 

    var goodCard = [Card]() 

    for (cardName, cardType) in nameType { 
     let cardText = nameText[cardName]! 
     let cardColor = nameColor[cardName]! //fatal error: unexpectedly found nil while unwrapping an Optional value 

     goodCard.append(Card(name: cardName, type: cardType, textt: cardText, colorr: cardColor)) 
    } 

    if typee != "" { 
     let redDogs = goodCard.filter {$0.type == typee} 
     print(redDogs) 
    } 
+0

的可能的複製[確定 「無」 在JSON值](http://stackoverflow.com/questions/34509114/determine-nil-value-in-json) – ColGraff

回答

0

您應該儘量避免使用強制展開運算符!。如果你使用它並且Optionalnil那麼當你使用這個變量時它會拋出異常。而是使用optional binding解開的值:

// optional binding 
if let cardColor = nameColor[cardName] { 
    // do something with the value 
}