Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Object-Oriented Swift Complex Data Structures Custom Initializers

I am not clear with init and self concepts.

truct RGBColor { let red: Double let green: Double let blue: Double let alpha: Double

let description: String

init() {
    red = 86.0
    green = 191.0
    blue = 131.0
    alpha = 1.0
    description = "red: \(red), green: \(green), blue: \(blue), alpha: \(alpha)"

}

}

var color = RGBColor()

This is what the code I have written, do I have to make any changes

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

    let description: String

    init() {
        red = 86.0
        green = 191.0
        blue = 131.0
        alpha = 1.0
        description = "red: \(red), green: \(green), blue: \(blue), alpha: \(alpha)"

    }
}

1 Answer

Doing it this way will work, BUT you lose the dynamic nature of the code, the values are stored and will always be that way since you have them in the init, and also they are constants so you can't change them ever.

Try this out:

struct RGBColor {
    var red: Double
    var green: Double
    var blue: Double
    var alpha: Double

    let description: String

    init(colorForRed:Double,colorForGreen:Double,colorForBlue:Double,cantForgetAlpha:Double) {
        self.red = colorForRed
        self.green = colorForGreen
        self.blue = colorForBlue
        self.alpha = cantForgetAlpha
        description = "red: \(red), green: \(green), blue: \(blue), alpha: \(alpha)"

    }
}

You can change the value all you want now.

Thank you so much. I even understood the concept.

You're welcome...glad I could help.