Let’s write a simple class to explain in my head :
class SomeClass {
var happyToUsed = 10
}
And create an object
let someObject = SomeClass()
and use its property for case 1:
someObject.happyToUsed // prints 10
for case 2:
someObject.self.happyToUsed // prints 10
and case 3
someObject.self.self.self.self.happyToUsed // prints 10 compiler is still ok, even if self count 1k
I know case 1 and case 2 is same ( directly point the same object ). Even if I have used SomeClass.self rather than objects cases will act the same way. I ever used case 3 in a project so far.
My question is there any example case 3 which I should prefer or negative effect on memory management?
2
Answers
This is a Postfix Self Expression according to the Swift reference:
The fact that you can write
.self
indefinitely is just a side effect of this definition. Sincex.self
is an expression itself, you can add.self
to it too. And you can do this forever.That doesn’t mean you should though.
These do the same thing:
Hopefully you’d agree that the second one reads better. Similarly,
.self
is generally redundant. According to this discussion, it seems like.self
is really just a legacy from Objective-C. IMO it also makes syntaxes like the identity key path (.self
) "make more sense".There are no differences between them, ultimately you are pointing to the same instance; Classes are reference types so whatever happens, it will always point to the same reference; You don’t need to repeat it as it takes the same location in the memory which is already reserved.