【发布时间】:2014-08-19 23:50:26
【问题描述】:
可能我没看清楚可选值:
class func albumsWithJSON(allResults: NSArray) -> [Album] {
var albums = [Album]()
if allResults.count>0 {
for result in allResults {
var name = result["trackName"] as? String
if name == nil {
name = result["collectionName"] as? String
}
var price = result["formattedPrice"] as? String
if price == nil {
price = result["collectionPrice"] as? String
if price == nil {
var priceFloat: Float? = result["collectionPrice"] as? Float
var nf: NSNumberFormatter = NSNumberFormatter()
nf.maximumFractionDigits = 2;
if priceFloat != nil {
price = "$"+nf.stringFromNumber(priceFloat)
}
}
}
let thumbnailURL = result["artworkUrl60"] as String
let imageURL = result["artworkUrl100"] as String
let artistURL = result["artistViewUrl"] as? String
var itemURL = result["collectionViewUrl"] as? String
if itemURL == nil {
itemURL = result["trackViewUrl"] as? String
}
var newAlbum = Album(name: name!, price: price!, thumbnailImageURL: thumbnailURL, largeImageURL: imageURL, itemURL: itemURL!, artistURL: artistURL!)
albums.append(newAlbum)
}
}
}
在这一行,我得到“在展开可选值时意外发现 nil”错误:
var newAlbum = Album(name: name!, price: price!, thumbnailImageURL: thumbnailURL, largeImageURL: imageURL, itemURL: itemURL!, artistURL: artistURL!)
显然 JSON 中缺少一些信息,但我该如何处理缺失值?
【问题讨论】:
标签: swift