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?
This is a Postfix Self Expression according to the Swift reference:
A postfix self expression consists of an expression or the name of a type, immediately followed by
.self
The first form evaluates to the value of the expression. For example, x.self evaluates to x.
The fact that you can write .self
indefinitely is just a side effect of this definition. Since x.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:
let x = 10
let x = 10
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With