Ion Mardari
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!

    Ion Mardari

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade