Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialBryan Beasman
3,435 PointsSwift: 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.
1 Answer
Thomas Dobson
7,511 PointsBryan,
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
Bryan Beasman
3,435 PointsThank you, Thomas!
Bryan Beasman
3,435 PointsBryan Beasman
3,435 PointsAlso, some of my code appears to show up outside of the code area in this discussion.