Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using useless object.self.self.. or Class.self.self.. is ever need?

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?

like image 320
zeytin Avatar asked Dec 19 '20 11:12

zeytin


2 Answers

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".

like image 176
Sweeper Avatar answered Sep 28 '22 10:09

Sweeper


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.

like image 41
Menaim Avatar answered Sep 28 '22 08:09

Menaim