Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS

Bryan Beasman
Bryan Beasman
3,435 Points

Swift: Do Classes NEED initializer methods?

Hello,

I recently finished the Object Oriented Swift course in the Beginner iOS Development track. So, I know with Structs a member wise initializer method is created for you but with a class you have to manually build one. My question is, if your stored properties all have default values, do you even need to build an initializer method? For example:

class Flashlight { var isOn: Bool = false

func turnFlashlight(_ key: String) {
    if key == "on" {
        isOn = true
    } else if key == "off" {
        isOn = false
    } else {
        print("Error: You cannot turn a flashlight \(key)")
    }
}

}

The above code runs just fine for me, but it does not include an initializer. Now look at this code:

class Flashlight { var isOn: Bool

init() {
    isOn = false
}

func turnFlashlight(_ key: String) {
    if key == "on" {
        isOn = true
    } else if key == "off" {
        isOn = false
    } else {
        print("Error: You cannot turn a flashlight \(key)")
    }
}

}

The code above includes an initializer to set my stored property. I get the same results.

Which is best practice? Should I always use an initializer? Or can I omit it in cases like this? I want to follow best practice.

Bryan Beasman
Bryan Beasman
3,435 Points

Also, some of my code appears to show up outside of the code area in this discussion.

1 Answer

Thomas Dobson
Thomas Dobson
7,511 Points

Bryan,

According to apple documentation:

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.

I might recommend reading the Initalization Docs