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 trialRamses Toledo
1,973 PointsWhat it's the difference between using an Initializer and giving stored properties an initial value?
Hello everyone.
I'm kind of confuse on why to use an Initializer instead of giving initial values to the stored properties on a Struct or class.
Thanks!!!
2 Answers
Steve Hunter
57,712 PointsHi Ramses,
If you use a value for each property, every instance of the class or struct will look the same.
Using an initializer allows you to make them individual.
class Car {
var color: String
var engineSize: Int
init(color: String, engineSize: Int){
self.color = color
self.engineSize = engineSize
}
}
So in the above weak example you can create cars of any colour or engine size.
let slowBlueCar = Car(color: "Blue", engineSize: 1200)
let fastRedCar = Car(color: "Red", engineSize: 3500)
If you stipulated those with fixed values, then each instance would look the same. (You could then amend them, agreed!).
I hope that helps a little!
Steve.
Ramses Toledo
1,973 PointsThanks a lot Steve, I really appreciate your help!
Steve Hunter
57,712 PointsNo problem!
Ramses Toledo
1,973 PointsRamses Toledo
1,973 PointsThanks a lot Steve, you helped me a lot!!!! Is there's any way to change Stored properties after they got assigned with an initial value?
Steve Hunter
57,712 PointsSteve Hunter
57,712 PointsYes you can - as long as they are declared with
var
. If they are declared withlet
they are constants and cannot change their value.Steve.