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 trialhashemmaraqa
2,100 PointsI still don't understand why I need to use init. Using x twice in the video confused me.
I still don't understand why I need to use init. Using x twice in the video confused me.
1 Answer
jenko
8,562 PointsMore information on initialisers can be found in the official documentation here
Which provides the following description,
Initialization is the process of preparing an instance of a class, structure, or enumeration for use. This process involves setting an initial value for each stored property on that instance and performing any other setup or initialization that is required before the new instance is ready for use.
In the following example you will see that while we have declared that temperature is a double, we provide the init method which has an initial value. You could however have temperature = temperature within the init() which would in turn expect an input when Fahrenheit is called.
struct Fahrenheit {
var temperature: Double
init() {
temperature = 32.0
}
}
var f = Fahrenheit()
print("The default temperature is \(f.temperature)° Fahrenheit")
// Prints "The default temperature is 32.0° Fahrenheit"
This is my understanding, if anyone else has corrections or additions please post them.
hashemmaraqa
2,100 Pointshashemmaraqa
2,100 Pointshttps://teamtreehouse.com/library/initializers-and-self