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