I have a rss link which I parse it using SWXMLHash and then I use it's elements like below but when an element is missing in the rss I get below error message! how can I check if rss contain for example source element if it doesn't contain it put " " in the variable !
UPDATE : Fixed Code :
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
})
}
you should check for optional where you have force unwrap element, if it has element take value else put ""
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)")
This works when source or url is empty and prints Blank if one of them are empty