json缺少快速的领域

时间:2016-04-15 03:17:32

标签: arrays json swift

所以我有一个从json文件中提取数据并解析它的函数。它给我一个零错误,因为一些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)
    }

1 个答案:

答案 0 :(得分:0)

应尽可能避免使用强制解包运算符} 。如果您使用它并且!Optional,那么当您使用该变量时,它将引发异常。而是使用optional binding来解包值:

nil