In ObjectiveC we create objects like
-(instancetype)init()
{
return [super init]; // Here it returns initialised value
}
Class *obj = [[Class alloc]init]
But swift initialiser wont 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 a type are correctly initialized before they are used for the first time.
init()
{
super.init()
}
let obj = Class()
Now how swift initialiser returns the instance to variable obj
?.
How the allocation and initialisation occurs in swift?
Performance. The official Apple website claims that Swift is 2.6 times faster than Objective-C. However some studies indicate that the difference is not as dramatic. Swift and Objective-C are both statistically typed languages that use the same iOS SDK and the high-quality Low Level Virtual Machine compiler.
Swift init() Initialization is the process of preparing an instance of a class, structure, or enumeration for use. This process involves setting an initial value for each stored property on that instance and performing any other setup or initialization that is required before the new instance is ready for use.
That's where the @objc attribute comes in: when you apply it to a class or method it instructs Swift to make those things available to Objective-C as well as Swift code.
An initializer is a special type of function that is used to create an object of a class or struct. In Swift, we use the init() method to create an initializer. For example, class Wall { ... // create an initializer init() { // perform initialization ... } }
As @NikolayKasyanov says, with the init family of initialisers, the return (of self
) is implicit, and you can't return nil
. However, if you want to initialise an optional that could return nil
, use a 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
}
}
}
It's just a convention. Swift initialiser sets up a valid instance and could not theoretically return anything other that a valid instance, so there's no point in explicit return.
So (from my point of view) allocation & initialisation sequence looks like this:
self
set to allocated instanceAlthough this approach breaks some useful Objective-C patterns like initialisers returning nil
on error, the guarantee that instantiation always succeeds allows compiler to perform some optimisations. Also without dropping initialisers returning nil
it would be impossible to actually remove nil
from language, it would seem weird if initialisers were returning optionals.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With