I'm having problem checking if the xml element has desire tag or not :
I wrote my code like below :
//checking if link is empty
if xml["rss"]["channel"]["item"][index]["source"].element!.attributes["url"] != "" {
Link = (xml["rss"]["channel"]["item"][index]["source"].element?.attributes["url"])!
} else {
Link = ""
}
When I run this code i get error of : Thread3 EXC_BAD_INSTRUCTION
, for the first line of my code ,but when I run the code like below :
it goes through if and does not understand that source element is not exist at all!
code :
//checking if link is empty
if (xml["rss"]["channel"]["item"][index]["source"].element?.attributes["url"] as String?) != nil {
Link = (xml["rss"]["channel"]["item"][index]["source"].element?.attributes["url"] as String?)!
} else {
Link = ""
}
How check if source element is exist or not in swift 2 ?
FullCode :
let xml = SWXMLHash.parse(data)
//one root element
let count = xml["rss"]["channel"]["item"].all.count
print(count)
var Name = ""
var Image = ""
var Link = ""
var Time = ""
for var index = 0; index < count; index++ {
Name = xml["rss"]["channel"]["item"][index]["title"].element!.text!
Image = (xml["rss"]["channel"]["item"][index]["description"]["img"].element?.attributes["src"])!
//checking if time is empty
if let check_time = xml["rss"]["channel"]["item"][index]["pubDate"].element?.text! as String? {
Time = check_time
}else{
Time = ""
}
//checking if link is empty
if let element = xml["rss"]["channel"]["item"][index]["source"].element?.attributes["url"] as String? where element != "" {
print("salalalalam")
print(Link)
Link = element
} else {
Link = ""
}
In your first snippet it seems the element to be nil, so your code crash. In your second snippet (because the element is nil) it simply pass trough.
How to use conditional optional binding in Swift ?
let i:[Int?] = [1,2,10, nil]
i.forEach { v in
if let x = v where x != 10 {
print("value passed the test:", x)
} else {
print("didn't pass the test:", v)
}
}
/*
value passed the test: 1
value passed the test: 2
didn't pass the test: Optional(10)
didn't pass the test: nil
*/
UPDATE, based on your notes
if let url = xml["rss"]["channel"]["item"][index]["source"].element?.attributes["url"] {
Link = url
} else {
Link = ""
}