我有一个rss链接,我使用SWXMLHash解析它,然后我使用它的元素,如下面但是当rss中缺少一个元素时,我得到以下错误消息! 我如何检查rss是否包含例如源元素,如果它不包含它" "在变量!
更新: 固定代码:
let count = xml["rss"]["channel"]["item"].all.count
var Name = ""
var Image = ""
var Link = ""
for var index = 0; index < count; index++ {
Name = xml["rss"]["channel"]["item"][index]["title"].element!.text!
if let element = xml["rss"]["channel"]["item"][index]["source"].element?.attributes["url"] as String? {
Image = element
Link = element
} else {
print("Blank")
Image = ""
Link = ""
}
let ap = pic(name: Name ,img : Image, link : Link)
self.tableData.append(ap)
//for reducing delay of loading table view data
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
return
})
}
答案 0 :(得分:2)
你应该检查你有强制解包元素的可选项,如果它有元素值,否则放“”
let count = xml["rss"]["channel"]["item"].all.count
let arrSource:NSMutableArray = []
for var index = 0; index < count; index++ {
if let element = xml["rss"]["channel"]["item"][index]["source"].element?.attributes["url"] as String? {
print("Element \(element)")
arrSource.addObject(element)
} else {
print("Blank")
}
}
print("Count \(arrSource.count) Arr \(arrSource)")
这在源或网址为空时有效,如果其中一个为空则打印空白