I am struggling with a nice pattern about handling multiple optionals in my code and the corresponding error handling.
Hava a look at the following example
func getCoordinates1(pLatitude: Double?, pLongitude: Double?) -> CLLocationCoordinate2D?{
var coord:CLLocationCoordinate2D?
if let latitude = pLatitude {
if let longitude = pLongitude {
coord = CLLocationCoordinate2DMake(lat, long)
}
}
return coord
}
This looks fine, but in a real world, you might need some error handling and here I am looking for a nice way of writing it down without duplicate code:
func getCoordinates2(pLatitude: Double?, pLongitude: Double?) -> CLLocationCoordinate2D? {
var coord:CLLocationCoordinate2D?
if let latitude = pLatitude {
if let longitude = pLongitude {
coord = CLLocationCoordinate2DMake(latitude, longitude)
} else {
// do something to catch the error
}
} else {
// do the same as above (duplicate code)
}
return coord
}
What I sometimes do is that I use a boolean to keep track of it:
func getCoordinates3(pLatitude: Double?, pLongitude: Double?) -> CLLocationCoordinate2D? {
var coord:CLLocationCoordinate2D?
var success = false
if let latitude = pLatitude {
if let longitude = pLongitude {
coord = CLLocationCoordinate2DMake(latitude, longitude)
success = true
}
}
if !success {
// do something to catch the error
}
return coord
}
Or I use the pattern of exiting early, but I think this is also erroneous
func getCoordinates4(pLatitude: Double?, pLongitude: Double?) -> CLLocationCoordinate2D? {
if let latitude = pLatitude {
if let longitude = pLongitude {
return CLLocationCoordinate2DMake(latitude, longitude)
}
}
// do something to catch the error
return nil
}
Of course this is a striped down example with only two optionals, but when parsing json, a lot more cascading-if might be necessary. I hope the idea and the problem is clear.