Reputation: 1099
I am trying to do this exercise. I keep getting errors.
"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.
My code:
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
}
override convenience init() {
//I can figure this part out, no problem.
}
// I cannot figure out the next part.
Upvotes: 3
Views: 143
Reputation: 59536
So you need to provide an initializer to create an equilateral 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 = sideC
}
convenience init(equilateralWithEdge edge:Int) {
self.init(sideA: edge, sideB: edge, sideC:edge)
}
}
Now you can build an equilateral Triangle writing
let triangle = Triangle(equilateralWithEdge: 10)
Test
triangle.sideA // 10
triangle.sideB // 10
triangle.sideC // 10
Upvotes: 1
Reputation: 2745
Since you're saying you can figure out the insides of the convenience init yourself:
Add a parameter to your convenience init, remove the override
unless you're overriding something (doesn't look like it), and close the class definition with a }
. You're done.
Upvotes: 1
Reputation: 274423
You seem to be stuck on the convenience init part.
As the question suggests, your initializer for equilateral triangles should take 1 parameter, so let's add one:
convenience init(sideLength: Int) {
}
Every convenience inititalizer must call a designated constructor or another convenience constructor. In this case, you can just call the other designated constructor that takes 3 parameters.
convenience init(sideLength: Int) {
self.init(sideA: ???, sideB: ???, sideC: ???)
}
You're almost done. You just need to figure out the parameters.
I think at this point you can guess what the three parameters are. Have a go!
Answer here:
self.init(sideA: sideLength, sideB: sideLength, sideC: sideLength)
Upvotes: 1