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 Intermediate Swift Object Initialization Initializer Delegation

Jialong Zhang
Jialong Zhang
9,821 Points

Initializer Delegation Unknown second initializer error

struct Point{
    let x: Int = 0
    let y: Int = 0
}

struct Size{
    let width: Int = 0
    let height: Int = 0
}

struct Rectangle{
    var origin = Point()
    var size = Size()
    init(origin: Point, size: Size){
        self.origin = origin
        self.size = size
    }
    init(x: Int, y: Int, width: Int, height: Int){
        let origin = Point(x: x, y: y)
        let size = Size(width: width, height: height)
        self.init(origin: origin, size: size)
    }
}
Heidi Puk Hermann
Heidi Puk Hermann
33,366 Points

so, there is a few error in your code.

  1. in the structs Point and Size, you define constants with a value of 0, meaning they can never be anything else. There are two solutions to this; either define them as variables or just don't give them an initial value.
  2. in the Rectangle struct, you should just define the type of your variables as Point and Size respectively. Which also leads to:
  3. your second initializer is constructed wrong. you should define self.origin and self.size.

I have attached a working code, where the errors have been fixed :)

struct Point{
    let x: Int
    let y: Int
}

struct Size{
    let width: Int
    let height: Int
}

struct Rectangle{
    var origin: Point
    var size: Size
    init(origin: Point, size: Size){
        self.origin = origin
        self.size = size
    }
    init(x: Int, y: Int, width: Int, height: Int){
        self.origin = Point(x: x, y: y)
        self.size = Size(width: width, height: height)
    }
}

3 Answers

Jialong Zhang
Jialong Zhang
9,821 Points

thank you for your answer. I just wondering about the wrong codes. I followed the exact same code in the video.

Heidi Puk Hermann
Heidi Puk Hermann
33,366 Points

so, I just redid the video, and it is "my point 1" thats different between your code and his. He uses variables instead of constants. In that case, the rest of your code should work fine then. :)

Jialong Zhang
Jialong Zhang
9,821 Points

Thanks for your answer. How can I mark your answer as best answer