How does "if" receive a "false" value from "let" assigning a "nil" value?

Content Warning : Noob Question

How does "if" receive a "false" value from the "let" in the code in the screen shot here:


I tried to break it down myself and got stuck.

I thought maybe "nil" is interpreted as "false" by "let" but that isn't the case as seen in the screen shot.

Is "if let" a special combined keyword that can handle "nil" as "false"?

I'm not seeing how or from where "if" is getting the "false" Bool value to know to go to the else clause, please.

Thank you for your time.

:rainbow::pray::rainbow:

if let is a special form in the language (as with guard let, for let, while let, case let, etc.).

It's specifically designed to conditionally unwrap the right hand of the =, and assign it to the left side only if it's not nil.

There's no explicit bool you can get at in the middle of that. E.g. you couldn't do:

let x: Bool = let somePlanet(rawValue: positionToFind)
1 Like

You're thinking of if let as being some sort of complex sugar for if <bool>, but that's not the right way to think about it. Among other things, it can't possibly work — if let binds a variable that's in scope within the if block, and there's no way to get that from if <bool>. It's better to think of it the other way around: an if statement tests an expression against a pattern and succeeds if it matches. if case is the most general form of that, where you can write an arbitrary pattern. if let uses a specific pattern, which tests for an optional .some. if <bool> is even more specific than that: the pattern is just the value true.

6 Likes

@John_McCall , @AlexanderM Thank you.

I also found this page. Which was helpful. But I'm not sure what the author means by "club" and "clubbed" maybe "group" and "grouped"? (Were they using google translate?) Also the page locks up at the end. Shame.

:rainbow::pray::rainbow:

Note that this is very similar to C++ where pointers, ints and pretty much everything else can be used in bool context:

#define let const auto

if (let planet = getPlanet()) {
    planet->explore(); // p is not null here
}
1 Like