Arrays json缺少字段swift

Arrays json缺少字段swift,arrays,json,swift,Arrays,Json,Swift,所以我有一个函数,可以从json文件中提取数据并对其进行解析。这给我带来了一个nil错误,因为一些json条目没有“colors”字段/数组。我将如何解释这一点,并将“错误”作为未解释的文本输入 func getData2(){ let dataPath = NSBundle.mainBundle().pathForResource("cardata", ofType: "json") if let JSONData = NSData(contentsOfFile: dat

所以我有一个函数,可以从json文件中提取数据并对其进行解析。这给我带来了一个nil错误,因为一些json条目没有“colors”字段/数组。我将如何解释这一点,并将“错误”作为未解释的文本输入

  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)
    }

应避免使用强制展开运算符
只要可能。如果使用该变量且
可选
nil
,则使用该变量时将引发异常。而是使用展开值:

// optional binding
if let cardColor = nameColor[cardName] {
  // do something with the value
}
可能重复的