What is .self after a class name used for? Swift 3
Asked Answered
B

1

6

I recently noticed that some codes do init of instances like ClassName.self() for example:

let realm = try! Realm.self()

From the output and the usage thereafter, it is just like as though without it - Realm()

Is there any specific reason or usage for doing an init with .self?

Beaming answered 12/12, 2016 at 9:3 Comment(2)
Do you have a reference where self() is used like that? On realm.io/docs/swift/latest I can see only let realm = try! Realm() – and it should make no difference.Scammony
@MartinR It is actually from codes passed on to me, like I mentioned in the question, usage after such a declaration is as normal, e.g. try! realmUpdate.write so I could not understand why is there a need for the .self during the declaration.Beaming
L
1

This is somewhat speculation, but I believe the places that do use Type.self() in the context of Realm follows a misperceived convention that has followed (some irrelevantly) the effects of Swift team resolving the bug

The following commit by the Realm team was in preparation for the anticipated resolution of the bug above:

It's possible that the changes in the commit above (Type updated to Type.self, in proper context) has inspired code bases that make use of Realm to also make use of Type.self in initializer context, i.e., Type.self(). This is, however, a redundant use of the .self suffix.

Loper answered 12/12, 2016 at 9:29 Comment(4)
So it is just like adding self when using the class owned parameters - e.g. self.frame. Not wrong but does not do anything?Beaming
@BenOng In that context, sometimes we're required to use the self suffix, e.g. to help the compiler differentiate between class owned parameters and same-named local parameters (commonly used in e.g. initializer, self.foo = foo). But yes, the use of self in the context you describe is redundant, and I see no reason for it; a similar case would be using e.g. Realm.init() rather than Realm() (the .init does have its uses, but is also only redundant, in some cases).Loper
Thank you so much for the quick answer! I'll accept this until I find another reason for the use of .selfBeaming
@BenOng Happy to help.Loper

© 2022 - 2024 — McMap. All rights reserved.