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 2.0 Complex Data Structures Custom Initializers

Kurt Lyell
Kurt Lyell
2,892 Points

Using self in init().

For this code challenge why do you not use self.description? I would think this block of code would work and do not understand why you would not use self.description, at least to keep the code neat.

init(red: Double, green: Double, blue: Double, alpha: Double) { self.red = red self.green = green self.blue = blue self.alpha = alpha description = "red: (red), green: (green), blue: (blue), alpha: (alpha)" }

The correct code is down below for the code challenge. So what is the big difference here? Also why do you have to do this?

"red: (red), green: (green)

init(red: Double, green: Double, blue: Double, alpha: Double) { self.red = red self.green = green self.blue = blue self.alpha = alpha description = "red: (red), green: (green), blue: (blue), alpha: (alpha)" }

structs.swift
struct RGBColor {
    let red: Double
    let green: Double
    let blue: Double
    let alpha: Double

    let description: String

    // Add your code below
    init(red: Double, green: Double, blue: Double, alpha: Double) {
        self.red = red
        self.green = green
        self.blue = blue
        self.alpha = alpha
        description = "red: \(red), green: \(green), blue: \(blue), alpha: \(alpha)"
    }



}

1 Answer

Greg Kaleka
Greg Kaleka
39,021 Points

Hi Kurt,

In Swift, you're welcome to use self or not in initializers. The way you've written your init method, you need to use self for red, green, blue and alpha, because you've passed in parameters with those names. For description, though, you don't need to, because there's no ambiguity about which description you're referring to - there's only one. If you prefer, you're certainly welcome to use self.description, but it's not required by Swift.

Cheers,

-Greg