3

Let's say I have a class:

class Fruit {
    var fruitName: String

    init(getFruit name: String) {
        fruitName = name
    }

}

Is there any difference between using the constructor, and using .init?

var apple = Fruit(getFruit: "apple")
var orange = Fruit.init(getFruit: "orange")

Im not seeing any difference in playground. enter image description here

I apologize if the question is badly worded or has been asked before.

leedex
  • 963
  • 8
  • 19
  • Both are calls to the initializer as there are no constructors in Swift, only initializers and it's just syntactic sugar that you can omit the explicit `.init` call. – Dávid Pásztor Mar 10 '18 at 01:36
  • 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:54

2 Answers2

5

From the Initializer Expression section of the language guide:

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

Initializing using the explicit .init on the type directly is no different than without it; they are equivalent from Swift's perspective, so most folks prefer the brevity of omitting .init.

Itai Ferber
  • 28,308
  • 5
  • 77
  • 83
1

To my knowledge, there is absolutely no difference.

It is generally convention in Swift to call the constructor without the .init This is the 'swiftier' shorthand.

Rudy B
  • 579
  • 1
  • 3
  • 16