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

Jjjjsl Dlsiehd
Jjjjsl Dlsiehd
928 Points

I can't compile my code. what is wrong?

like in the title

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, description: String){
        self.red = 86.0
        self.green = 191.0
        self.blue = 131.0
        self.alpha = 1.0
        self.description = ("red" + ":" + self.red + "," + "green" + ":" + self.green + "," + "blue" + ":" + self.blue + "," + "alpha" + ":" + self.alpha)
    }
}

2 Answers

Kristof Kocsis
Kristof Kocsis
15,455 Points

Few thing I'd like to point out:

  1. Inside the init method don't hardcode the values since that kills the point of an init value.
  2. When you create the init method you don't need to ask for the description since you'll create that from the R G B values.
  3. instead of concatenating the strings use string interpolation.
  4. Be mindful when you use self

With that said, here is the code:

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
        self.description = ("red: \(red), green: \(green), blue: \(blue), alpha: \(alpha)")
    }
}
Jjjjsl Dlsiehd
Jjjjsl Dlsiehd
928 Points

Thanks, now it's working. But for now, i think i don't understand what actually does init method. Can someone help me understand that with simple words? :)

PS: Sorry about my English :/

Kristof Kocsis
Kristof Kocsis
15,455 Points

An init method is used to initialize a struct or a class. Basically when you call this struct the init method is responsible asking you for the data that is required for the struct. You can think about it as a special func: it is a bridge between you and the struct.