Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is 'init' not assignable?

Tags:

swift

I just read that the init method can't be used as a value. Meaning:

var x = SomeClass.someClassFunction // ok
var y = SomeClass.init              // error

Example found on Language reference

Why should it be like that? Is it a way to enforce language level that too dirty tricks come into place, because of some cohertion or maybe because it interferes with another feature?

like image 447
Nicola Miotto Avatar asked Feb 12 '23 19:02

Nicola Miotto


1 Answers

Unlike Obj-C, where the init function can be called multiple times without problems, in Swift there actually is no method called init.

init is just a keyword meaning "the following is a constructor". The constructor is called always via MyClass() during the creation of a new instance. It's never called separately as a method myInstance.init(). You can't get a reference to the underlying function because it would be impossible to call it.

This is also connected with the fact that constructors cannot be inherited. Code

var y = SomeClass.init

would also break subtyping because the subtypes are not required to have the same initializers.

like image 98
Sulthan Avatar answered Feb 23 '23 02:02

Sulthan