0
0
Swiftprogramming~10 mins

Adding initializers via extension in Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to add a new initializer to the struct using an extension.

Swift
struct Rectangle {
    var width: Double
    var height: Double
}

extension Rectangle {
    init(squareSide: Double) {
        self.width = [1]
        self.height = squareSide
    }
}
Drag options to blanks, or click blank then click option'
Aheight
Bwidth
CsquareSide
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using uninitialized variables like width or height instead of the parameter.
Setting width or height to zero.
2fill in blank
medium

Complete the code to add a failable initializer in the extension that returns nil if the side length is negative.

Swift
struct Circle {
    var radius: Double
}

extension Circle {
    init?(diameter: Double) {
        guard diameter >= 0 else { return [1] }
        self.radius = diameter / 2
    }
}
Drag options to blanks, or click blank then click option'
Aself
Bnil
Cfalse
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Returning self or false instead of nil.
Not using a guard statement to check the condition.
3fill in blank
hard

Fix the error in the extension initializer by completing the missing keyword to call the memberwise initializer.

Swift
struct Point {
    var x: Double
    var y: Double
}

extension Point {
    init(value: Double) {
        [1] init(x: value, y: value)
    }
}
Drag options to blanks, or click blank then click option'
Areturn
Bsuper
Cinit
Dself
Attempts:
3 left
💡 Hint
Common Mistakes
Using super in a struct, which is invalid.
Omitting self and just writing init(...).
4fill in blank
hard

Fill both blanks to add an initializer in the extension that creates a rectangle with equal width and height.

Swift
struct Square {
    var width: Double
    var height: Double
}

extension Square {
    init(side: Double) {
        self.[1] = side
        self.[2] = side
    }
}
Drag options to blanks, or click blank then click option'
Awidth
Bheight
Cside
Dlength
Attempts:
3 left
💡 Hint
Common Mistakes
Using property names that do not exist like side or length.
Assigning values to the parameter name instead of properties.
5fill in blank
hard

Fill all three blanks to add an initializer in the extension that creates a color from RGB values between 0 and 255.

Swift
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
    }
}
Drag options to blanks, or click blank then click option'
Ar
Bg
Cb
D255
Attempts:
3 left
💡 Hint
Common Mistakes
Using the number 255 as a value instead of the parameters.
Not converting Int to Double before division.