Complete the code to add a new initializer to the struct using an extension.
struct Rectangle {
var width: Double
var height: Double
}
extension Rectangle {
init(squareSide: Double) {
self.width = [1]
self.height = squareSide
}
}The new initializer sets both width and height to the same value squareSide to create a square.
Complete the code to add a failable initializer in the extension that returns nil if the side length is negative.
struct Circle {
var radius: Double
}
extension Circle {
init?(diameter: Double) {
guard diameter >= 0 else { return [1] }
self.radius = diameter / 2
}
}self or false instead of nil.The failable initializer returns nil if the diameter is negative, indicating failure to create the instance.
Fix the error in the extension initializer by completing the missing keyword to call the memberwise initializer.
struct Point {
var x: Double
var y: Double
}
extension Point {
init(value: Double) {
[1] init(x: value, y: value)
}
}super in a struct, which is invalid.self and just writing init(...).In Swift, to call another initializer from an initializer, you use self.init(...).
Fill both blanks to add an initializer in the extension that creates a rectangle with equal width and height.
struct Square {
var width: Double
var height: Double
}
extension Square {
init(side: Double) {
self.[1] = side
self.[2] = side
}
}side or length.The initializer sets both width and height properties to the same side value.
Fill all three blanks to add an initializer in the extension that creates a color from RGB values between 0 and 255.
struct Color {
var red: Double
var green: Double
var blue: Double
}
extension Color {
init(r: Int, g: Int, b: Int) {
self.red = Double([1]) / 255.0
self.green = Double([2]) / 255.0
self.blue = Double([3]) / 255.0
}
}The initializer converts integer RGB values to Double between 0 and 1 by dividing by 255.