twilight2 twilight2 - 1 month ago 17
Swift Question

guard statement variable do not give me value

var country = ""
if placemark.country != nil{
country = placemark.country!
}
self.awareLocationDetaile.text = country


Try to convert this code guard statement

guard let country = placemark.country else{
return
}
self.awareLocationDetaile.text = country


but unfortunate country have no value if i use guard statement where if give me value . what am i missing ?

UPDATE :

CLGeocoder().reverseGeocodeLocation(location) { ( clPlacemark :[CLPlacemark]?,error : NSError?) in
if error != nil {
print(error)
}else{
if let placemark = clPlacemark?[0]{
// print(placemark)
//MARK:- we are a good programmer
// var country = ""
// if placemark.country != nil{
// country = placemark.country!
// }
// self.awareLocationDetaile.text = country


guard let country = placemark.country else{

return

}


self.awareLocationDetaile.text = country
}

}
}

Answer

The guard statement works exactly as it is supposed to work. You are not missing anything. It does what it is supposed to do, not what you want. Your first code sample can be written a lot easier as

self.awareLocationDetaile.text = placemark.country ?? ""

It seems you copied a comment that the queen wrote after she wrote her very first line of code at the age of 89. Note the royal "we":

//MARK:- we are a good programmer

On the other hand, the return statement inside the guard statement will return from the closure, so nothing after that will be executed.

Comments