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

Not 100% understanding these initializers

Hi there,

really struggling to get this task. any help would be greatly appreciated.

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

  let description: String

  // Add your code below

    init() {
        self.red = 1.1
        self.green = 2.3
        self.blue = 1.2
        self.alpha = 3.0
        self.description = "red: \(red), green: \(green), blue: \(blue), alpha: \(alpha)"
    }
}

2 Answers

Dhanish Gajjar
Dhanish Gajjar
20,185 Points

I would suggest revisiting the videos again and listening very closely :)

Hope the code below helps in understanding.

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) {
        self.red = red
        self.green = green
        self.blue = blue
        self.alpha = alpha

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

let newColor = RGBColor(red: 86.0, green: 191.0, blue: 131.0, alpha: 1.0)
newColor.description
Kanish Chhabra
Kanish Chhabra
2,151 Points

You don't need to initialize 'description' in the initializer method because it's value is definite. Initializer is used only for those variables and constants whose value is determined while creating and instance which isn't the case with 'description' Assign the value to 'description' out of the init method and you're good to go! Hope it helps

Regards Kanish