In my code I am being passed a dictionary. That dictionary can contain an error string. Like this
func handleSomething(_ json: [String: Any]) -> (Bool, String?) {
if let error = json["error"] as? String {
print("I have an error: \(error)")
return (false, error)
}
...
return (true, nil)
}
I would think this would be a good place to use guard, however the code is not as concise
func handleSomething(_ json: [String: Any]) -> Bool {
let error = json["error"] as? String
guard error == nil else {
print("I have an error: \(error!)")
return (false, error)
}
...
return (true, nil)
}
Is there a better way to do this so the assignment and check can be done in one line? If not is this the correct use of guard?
Update: Added return values to better illustrate the real intention of the question.