Is there difference between using a constructor and using .init?

后端 未结 2 365
长情又很酷
长情又很酷 2021-01-22 11:16

Let\'s say I have a class:

class Fruit {
    var fruitName: String

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

}

Is ther

2条回答
  •  温柔的废话
    2021-01-22 11:46

    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.

提交回复
热议问题