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 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.