Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift initializer doesn't return value?

Tags:

ios

swift

Swift documentation clearly says.

Unlike Objective-C initializers, Swift initializers do not return a value.

please explain below syntax.

let instanceOfString = String()

It does initialize a String object by calling the initializer and return it. Value get assigned to instanceOfString. Isn't it?

like image 312
Swift Hipster Avatar asked Oct 22 '15 16:10

Swift Hipster


1 Answers

The swift documentation refers to the syntax of a type's init methods.

The syntax omits a return type in the signature and the method usually does not contain a return statement:

init() {
}

Obviously the call of an initializer (String()) does return a value. The difference to Objective-C is that the init method in pure Swift types is not free to return a different object than the target of the method—it's always the implicitly allocated instance of the target type.

The only exception is that it's possible to return nil in failable initializers.

like image 162
Nikolai Ruhe Avatar answered Oct 19 '22 19:10

Nikolai Ruhe