5

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

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • 2
    It's just different ways of doing the same thing. Choose which is convenient for you. The new `Class()` or the old `Class.init()` which is Objective-C like. – Suh Fangmbeng Mar 12 '19 at 06:08

2 Answers2

10

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.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • 1
    It makes a tiny difference in the Xcode editor: With the `SomeType.init(...)` syntax you can always “jump to definition,” even if the init method has no external parameter names (https://stackoverflow.com/q/32048978/1187415). That's why I use it sometimes *temporarily* to find out which init method (from multiple overloads) is actually used. – Martin R Mar 12 '19 at 07:49
2

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

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

AppleCiderGuy
  • 1,249
  • 1
  • 9
  • 16