top | item 45700469

(no title)

timsneath | 4 months ago

Ha! 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.

discuss

order

CBMPET2001|4 months ago

I've seen that exact pattern used to safely unwrap a weakly captured 'self' within a closure (to avoid retain cycles)

viktorcode|4 months 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.

saagarjha|4 months ago

It’s nil in Swift, and what the other comment said ;)