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

someone guide me down the write path i don"t know how i got lost

its saying don't use member initializers but why though

structs.swift
struct RGBColor {
    let red: Double
    let green: Double
    let blue : Double
    let alpha: Double
    let description : String
    init(red: Double, green: Double, blue: Double, alpha: Double, description: String)
        { self.red = 86.0
            self.green = 191.0
            self.blue = 131.0
            self.alpha = 1.0
            self.description = "red, green, blue, alpha"
    }

below

1 Answer

Hi Terrell,

First up, the initializer doesn't set the values of the member variables to hard-coded numbers - the initializer takes the values passed into it, and applies those to the member variables.

Taking that first step, the init method looks like:

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

We're not done yet, though!

The description member variable is created inside the init method. It uses the values passed in to generate a string using string interpolation. Adding that gives us:

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

I hope that makes sense!

Steve.

why you don at description to init like alpha:Double

You don't add description in the init`` method as a parameter as it can be generated by using the other parameters. The code can construct thedescription``` from the other parameters so let's not ask the user to do it!

The struct is complete once the init method has run as all its stored properties have a value. Those values don't have to come from outside of the struct - there's nothing wrong with calculating some or all from existing information.