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
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.
Class()
is just a shorthand for Class.init()
Both are interpreted by the compiler as exactly the same statements with no difference at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With