Saman Ray
Saman Ray

Reputation: 115

Why do we need to specify init method?

The following block of code runs fine even without specifying the init method. If this is the case, what purpose does the init method serve?

struct Person {
    var name: String
    var age: Int

    init(name: String, age: Int){
        self.name = name
        self.age = age
    }

}

let somePerson = Person(name: "Sam", age: 21)
somePerson.name
somePerson.age

Thank you your feedback.

Upvotes: 2

Views: 138

Answers (3)

Duyen-Hoa
Duyen-Hoa

Reputation: 15784

It's the behavior of Struct in swift.

See (Memberwise Initializers for Structure Types) in https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html

"Structure types automatically receive a memberwise initializer if they do not define any of their own custom initializers. Unlike a default initializer, the structure receives a memberwise initializer even if it has stored properties that do not have default values."

If you do not specify any memberwise init method, it will create for you. The init that you declare allow you to do more than just an simple init. For example:

struct Person {
    var name: String
    var age: Int

    init(name: String, age: Int){
        self.name = name.uppercaseString()
        self.age = age + 22
        //and more works ...
    }

}

Upvotes: 1

zneak
zneak

Reputation: 138171

You don't need it (anymore). Memberwise initialization is a new feature of Swift 2.2. The author either wrote this code for an earlier version of Swift or didn't know that it's no longer necessary.

Upvotes: 0

Daniel K
Daniel K

Reputation: 1129

As pointed out in this doc

Swift initializers

Swift provides a default initializer for any structure or class that provides default values for all of its properties and does not provide at least one initializer itself. The default initializer simply creates a new instance with all of its properties set to their default values.

Structure types automatically receive a memberwise initializer if they do not define any of their own custom initializers. Unlike a default initializer, the structure receives a memberwise initializer even if it has stored properties that do not have default values.

So if you write one init method, then you MUST write the default initializer yourself, if you want it to exist.

If you only need the default initializer, then you can omit it.

Upvotes: 1

Related Questions