Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Initializers in a single class (swift)

Create a Triangle class with properties to store the length of each side. Triangles are called scalene when all three sides are of different lengths, isosceles when two sides have the same length, or equilateral when all three sides have the same length.

Create an initializer for your class that takes three arguments and properly sets the class properties. Next, create a second initializer to use when your triangle is equilateral. Remember that all three sides will be the same length, so this method should only take one argument, but should still set all three properties. Try writing this initializer as a designated initializer first and then convert it to a convenience initializer. Finally, we want an initializer for isosceles triangles that takes two arguments. Think about how you should set up the external names for your parameters to make it clear which value will be used for two sides

This question confuses me so much. My question is: How am I supposed to create an init of isosceles and scalene in a single class? Or am I supposed to create another class? I need help. I'm new to Swift. Here's what I've got so far.

class Triangle {

    var sideA: Int
    var sideB: Int
    var sideC: Int

    init(sideA: Int, sideB: Int, sideC: Int) {

        self.sideA = sideA
        self.sideB = sideB
        self.sideC = sideC
    }

    convenience init(equilateralWithEdge edge:Int) {
        self.init(sideA: edge, sideB: edge, sideC:edge)
    }

}
like image 528
AllocSystems Avatar asked Oct 18 '22 20:10

AllocSystems


1 Answers

Here's how you can add another initializer to the same class that will use two parameters to create an Isosceles triangle:

class Triangle {

    var sideA: Int
    var sideB: Int
    var sideC: Int

    init(sideA: Int, sideB: Int, sideC: Int) {

        self.sideA = sideA
        self.sideB = sideB
        self.sideC = sideA
    }

    init(sideA: Int, sideB: Int) {

        self.sideA = sideA
        self.sideB = sideB
        self.sideC = sideB
    }

    convenience init(equilateralWithEdge edge:Int) {
        self.init(sideA: edge, sideB: edge, sideC:edge)
    }

}
like image 99
Andy Obusek Avatar answered Oct 21 '22 03:10

Andy Obusek