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 Classes and Their Methods

I am getting a compile error with self.price = price

I am getting a compile error with self.price = price and I don't know why.

I have the exact same code as Amit in the video

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

    init(title: String, price: Double) {
        self.title = title
        self.price = price // cannot assign 'price' in 'self
    }

    func discountedPrice(percentage: Double) -> Double {
        return price - (price * percentage / 100)
    }

}

let quadcopter = Product(title: "Quadcopter", price: 499.99)

What am I doing wrong?

Thanks!

3 Answers

This error is the result of having given the constant price an initial value when it was declared, as opposed to 'title' which was not given an initial value. If you remove the = 0.0 from the third line declaring the constant price, then the error will go away.

Philippe Côté
Philippe Côté
1,850 Points

I think the video didn't show this error because Amit was running Swift 1.0 and we are today at version 1.2...

Just tried what you suggested and it worked. It was confusing cause the error wasn't indicated in the video and I was writing the code simultaneously and it came up for me.

Thanks for your help!

That's strange the video's demonstration didn't show this as an error.

  • No problem. I enjoy picking up a new iOS forum question and answering it before one of those 30,000 point moderator geeks answers it within like 30 seconds!

I was just starting to type pretty much the same thing when I noticed I didn't need to!

Good work!

Steve.