Using 'guard' statement for early exits in swift?
Example:
func validate(number: Int?) -> Bool {
if let _ = number {
return true
}
return false
}
print(validate(number: nil))
The example defines a function that checks if an optional number is nil or not using an 'if let' construct.
Solution:
func validateUsingGuard(number: Int?) -> Bool {
guard let _ = number else {
return false
}
return true
}
print(validateUsingGuard(number: nil))
In the solution, the 'guard' statement provides a clearer and more concise way to perform the validation.