5 ms·
guard let self = self else { return }
by ranie93 11mo ago
guard let self = self else { return }
- timsneath 11mo agoHa! But that's not semantically meaningful Swift code in any normal context, nor is it idiomatic. `self` is equivalent to `this` in C++, and is never normally null. You use this construct for unwrapping nullable fields, for example something like this: guard let httpResult else { return } Note that you don't need to assign the value to itself in modern Swift. This line takes an optional (httpResult?) and returns early if null. If not, you can use it with strong guarantees that it's not nullable, so no need for ? or ! to unwrap it later in the scope.
- CBMPET2001 11mo agoI've seen that exact pattern used to safely unwrap a weakly captured 'self' within a closure (to avoid retain cycles)
- saagarjha 11mo agoIt’s nil in Swift, and what the other comment said ;)
- viktorcode 11mo ago> But that's not semantically meaningful Swift code in any normal context, nor is it idiomatic. `self` is equivalent to `this` in C++, and is never normally null. It is, when `self` is captured weakly in a closure, and that closure is outliving the instance.
- akmarinov 11mo agoThis can now be guard let self else { return }
- mojuba 11mo agoThere's a shorter form of it: guard let self else { return } which annoyingly the AI's don't know about.
- serial_dev 11mo agoNot much better, to be honest.
- saagarjha 11mo agoMost use of this is misguided unfortunately :(
- jitl 11mo ago`guard let` is great what’s there to hate? The big problem with swift is “expression has ambiguous type” and “expression took too long to type check”. Those don’t trade in code aesthetics but are problems I’ve never had in another language.