Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Swift Optionals issue when not returning nil

I ran across something that (I think) is weird. Is this expected behavior, or a bug or oversight in the Swift language?

When declaring a function that returns an optional, you're supposed to return nil in non-matching cases. This way, you can use the if let conditional to check for the optional.

But as in the example below, if instead of a nil I accidentally return a false value, no errors are thrown. And the if conditional always prints "is divisible". Maybe there is no way for the compiler to catch this, but it seems like a very tricky bug to have to track down (assuming a much more complex example). Or maybe it's just because this is such a simple example with a bool return?

Anyway, wanted to see if anyone thought this is just behaving as it should...

func isDivisible(#dividend: Int, #divisor: Int) -> Bool? {
    if dividend % divisor == 0 {
        return true
    }
    // An optional is supposed to return nil.
    return false
}

if let divisible = isDivisible(dividend: 42, divisor: 9) {
    println("is divisible")
} else {
    println("is not divisible")
}

1 Answer

On further thought, I'm thinking the if let conditional is only to check that the value exists (i.e. is not nil)? In the case of my example, I guess I'd still need another conditional to make sure it's true.