Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between using class() and class.init() in swift [duplicate]

Tags:

swift

Why we need to use init method explicitly while we can create an object without it

class Details {

}

var obj = Details()
var obj = Details.init()

What's the difference between these two instance creations

like image 960
Gowtham Ravi Avatar asked Jan 02 '23 04:01

Gowtham Ravi


2 Answers

Both are allowed and are equivalent. As The Swift Programming Language says:

If you specify a type by name, you can access the type’s initializer without using an initializer expression. In all other cases, you must use an initializer expression.

let s1 = SomeType.init(data: 3)  // Valid
let s2 = SomeType(data: 1)       // Also valid

let s3 = type(of: someValue).init(data: 7)  // Valid
let s4 = type(of: someValue)(data: 5)       // Error

So, when you’re supplying the name of the type when instantiating it, you can either use the SomeType(data: 3) syntax or SomeType.init(data: 3). Most Swift developers would favor SomeType(data: 3) as we generally favor brevity unless the more verbose syntax lends greater clarity, which it doesn’t in this case. That having been said, SomeType.init(data: 3) is permitted, though it is less common in practice.

like image 158
Rob Avatar answered Jan 03 '23 18:01

Rob


Class() is just a shorthand for Class.init()

Both are interpreted by the compiler as exactly the same statements with no difference at all.

like image 34
AppleCiderGuy Avatar answered Jan 03 '23 18:01

AppleCiderGuy