Initialization process of Swift vs ObjC?

In ObjectiveC, we create objects such as

-(instancetype)init() { return [super init]; // Here it returns initialised value } Class *obj = [[Class alloc]init] 

But a quick initializer will not return any value.

From Swift docs

Unlike Objective-C initializers, Swift initializers do not return a value. Their primary role is to ensure that new instances of the type are properly initialized before they are used for the first time.

 init() { super.init() } let obj = Class() 

Now, how does a quick initializer return an instance of the obj ? Variable.

How is the selection and initialization in the shortcut line?

+6
source share
3 answers

This is just a convention. The initial Swift initializer sets up a valid instance and theoretically cannot return anything else that is a valid instance, so there is no explicit return.

So (from my point of view), the sequence of allocation and initialization is as follows:

  • Runtime allocates instance of requested class
  • The initializer is called with self set to the selected instance.
  • The initializer performs the configuration
  • Runtime returns an initialized instance for client code

Although this approach breaks down some useful Objective-C patterns, such as initializers that return nil on error, ensuring that instantiation always succeeds allows the compiler to perform some optimizations. Also, without discarding the initializers returning nil , it would be impossible to remove nil from the language, it would seem strange if the initializers returned options.

+1
source

As Nikilay Kasyanov says, with the initialization of the initializer family, the return (from self ) is implicit, and you cannot return nil . However, if you want to initialize an option that could return nil , use the class function. EG:

 class NumberLessThan5: Int { var myNumber: Int init (i: Int) { self.myNumber = i } class func createWithInt(i: Int) -> NumberLessThan5? { if i < 5 { return NumberLessThan5(i) } else { return nil } } } 
+2
source

Initializers do NOT return an explicit value because it is not called directly by the code (in fact, it returns a value that is not transparent to the user).

Initializers are called by memory allocation and object initialization code at run time, when creating a new instance for a certain type (type-structure or class). The runtime uses variable type data generated by the compiler to determine how much space is required to store an instance of the object in memory.

After allocating this space, the initializer is called as an internal part of the initialization process to initialize the contents of the fields. Then, when the initializer exits, the runtime returns a newly created instance.

+1
source

Source: https://habr.com/ru/post/972562/


All Articles