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 trial

iOS Object-Oriented Swift Classes and Objects Designated Initializer

Why 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
Stone Preston
42,016 Points

assigning 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
Chris Shaw
26,676 Points

The constructor actually overrules the constant altogether, see the below example which functions perfectly fine in Xcode 6.1.1.

class Product {
    let title: String = "[Unknown]"
    let price: Double = 99.0

    init(title: String, price: Double) {
        self.title = title
        self.price = price
    }
}

let tv = Product(title: "Samsung Smart TV", price: 10000.00)
Stone Preston
Stone Preston
42,016 Points

good 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