Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between create object with init and () in Swift [duplicate]

Tags:

swift

init

class A {

    private var value: Int

    init(value: Int) {
        self.value = value
    }
}

We have class A and what is the difference between I create this object by using A.init(value: 5) and A(value: 5)? Thanks

like image 523
Alan Avatar asked Oct 11 '17 07:10

Alan


1 Answers

There is no functional difference between the two. Both styles will call the same initializer and produce the same value.


Most style guides that I've seen prefer to leave out the explicit .init-part in favor of the shorter A(value:) syntax — that also resembles the constructor syntax in many other languages.

That said, there are some scenarios where it's useful to be able to explicitly reference the initializer. For example:

  • when the type can be inferred and the act of initialization is more important than the type being initialized. Being able to call return .init(/* ... */) rather than return SomeComplicatedType(/* ... */) or let array: [SomeComplicatedType] = [.init(/* ... */), .init(/* ... */)]

  • when passing the initializer to a higher order function, being able to pass "something".map(String.init) rather than "something".map({ String($0) })

Again, it's a matter of style.

like image 181
David Rönnqvist Avatar answered Oct 04 '22 23:10

David Rönnqvist