Aug 31, 2018 · 1 min read
Hi Bob. I was practicing using swift’s book exercises and I am struggling with guard let in one scenario.
Suppose I have a function:
func calculateArea(x: Double, y: Double) -> Double? {}
I need to write a guard statement that verifies each of the parameters is greater than zero and returns nil if not.
I don’t understand how can I write the guard statement.
guard let x = x > 0 else {return nil}This throws the following error:
Initializer for conditional binding must have Optional type, not ‘Bool’I can solve the exercise with an if statement though:
func calculateArea(x: Double, y: Double) -> Double? {
var area: Double? if x > 0 && y > 0 {
area = x * y
}
return area
} calculateArea(x: 3, y: -2)
Thank you for your time!