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

Richard Mason
Richard Mason
3,027 Points

Get error when leaving 'price' with a default value as in video

When using the following code:

class Product {
    let title: String
    let price: Double = 0.0

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

I get the error (on line: self.price = price):

Cannot assign to 'price' in 'self'

4 Answers

Holger Liesegang
Holger Liesegang
50,595 Points

I'm working with Xcode 7 beta 2 and the compiler wants to change the constant into a var:

Holger Liesegang
Holger Liesegang
50,595 Points

...and the example from the post you mentioned doesn't work any more, too:

Holger Liesegang
Holger Liesegang
50,595 Points

...that said Swift is still a big building site :)

Holger Liesegang
Holger Liesegang
50,595 Points

Hi Richard Mason !

You got this error because you already gave the constant "price" a value of 0.0 . To give "price" another value (e. g. in init) you will have to use a variable "price" instead of a constant "price".

...and Welcome to Treehouse, Richard :)

Richard Mason
Richard Mason
3,027 Points

Hi Holger!

Thanks very much for your response! Yep, what you are saying makes sense to me, but what is shown in the video is that Amit has set both 'title' and 'price' as constants (exactly the code I have written above) and yet he gets no error.

Also, according to this post it should be possible. So why am I getting an error? Has something changed in Xcode/Swift?

Richard Mason
Richard Mason
3,027 Points

Thanks Holger. Yep I'm just going to assume that Swift/Xcode has changed in this regard since the video was made! :)