3 ms·
Actually, in `if let x = someOptional`, you should rather see it like this: `if (let x = someOptional)`. If that second part were a function, it would be `() ->
by zapzupnz 8y ago
Actually, in `if let x = someOptional`, you should rather see it like this: `if (let x = someOptional)`. If that second part were a function, it would be `() -> Optional<T>`.
That is to say, the if statement is satisfied if the "result" of the "function" (if you follow me; clearly I don't mean it's actually a function in the implementation) returns .some(T) (not nil) rather than .none (nil).
That we can do an assignment with `let` is just syntactic sugar for:
if someValue != nil {
let x = someValue!
}
Basically, we want to know if the value is non-nil. There are instances where the result can be nil, and if so, nothing gets assigned. For example:
protocol Fruit { }
protocol SeededFruit: Fruit { }
protocol SeedlessFruit: Fruit { }
struct Mandarin: SeedlessFruit { }
let mandarin = Mandarin()
if let someFruit = mandarin as? SeededFruit { }
Okay, so the compiler will actually disallow this, but you get the basic idea: `mandarin` is not a SeededFruit, the cast will always be false, therefore someFruit will be nil, therefore the "result" of the "function" will be nil, which is counted as false.
The thing is, this isn't specific to the `let` keyword, either. You could just as easily define a new variable with the `var` command.
So `let` and `var` don't mean different things in different contexts and never have. Swift just allows them to be used as syntactic sugar in if statements.
- zapzupnz 8y agoJust a late addition to anybody who sees this, I tend to think of `if let` and `if var` statements in Swift as syntactic sugar for: switch someOptional { case .none: // whatever case .some(let x): // do stuff with x }