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 trialJuan Cabral
4,318 PointsWhy in the init method we can change title if it is a constant? Inside the class its behavior is like a variable?
For example in Java if I declare a constant inside a class it cannot be modified like the example provided below:
public class Product {
final String title = "";
public Product(String title){
this.title = title; //this is an error
}
1 Answer
Stone Preston
42,016 Pointsassigning a value to a constant property when you declare it sets its default value. if the constant is assigned a value during initialization that default value is ignored, and the value assigned in the init method is used instead.
from the Swift eBook:
You can set the initial value of a stored property from within an initializer, as shown above. Alternatively, specify a default property value as part of the propertyβs declaration. You specify a default property value by assigning an initial value to the property when it is defined.
Chris Shaw
26,676 PointsChris Shaw
26,676 PointsThe constructor actually overrules the constant altogether, see the below example which functions perfectly fine in Xcode 6.1.1.
Stone Preston
42,016 PointsStone Preston
42,016 Pointsgood catch, edited my initial post. looks like the values assigned at declaration are just default values that only stick if the property is not assigned a value in init