0
0
Swiftprogramming~10 mins

Mutating methods for value types 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 declare a mutating method that changes the value of a property.

Swift
struct Counter {
    var count = 0
    mutating func increment() {
        count [1] 1
    }
}
Drag options to blanks, or click blank then click option'
A+=
B-=
C*=
D/=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '-' instead of '+' to increment.
Not marking the method as mutating.
2fill in blank
medium

Complete the code to mark the method as mutating so it can modify the struct's property.

Swift
struct Point {
    var x = 0, y = 0
    [1] func moveBy(x deltaX: Int, y deltaY: Int) {
        x += deltaX
        y += deltaY
    }
}
Drag options to blanks, or click blank then click option'
Astatic
Bmutating
Cfinal
Doverride
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'static' which means the method belongs to the type, not instance.
Forgetting to mark the method as mutating.
3fill in blank
hard

Fix the error in the mutating method that tries to assign a new value to self.

Swift
struct Rectangle {
    var width: Int
    var height: Int
    mutating func doubleSize() {
        self [1] Rectangle(width: width * 2, height: height * 2)
    }
}
Drag options to blanks, or click blank then click option'
A-=
B==
C=
D+=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '==' instead of '=' causes a syntax error.
Trying to modify properties without marking the method as mutating.
4fill in blank
hard

Fill both blanks to create a mutating method that resets the point to origin.

Swift
struct Point {
    var x: Int
    var y: Int
    [1] func reset() {
        x [2] 0
        y = 0
    }
}
Drag options to blanks, or click blank then click option'
Amutating
Bstatic
C+=
D=
Attempts:
3 left
💡 Hint
Common Mistakes
Not marking the method as mutating.
Using '+=' instead of '=' to reset the value.
5fill in blank
hard

Fill all three blanks to create a mutating method that scales the size and updates the description.

Swift
struct Size {
    var width: Int
    var height: Int
    var description: String
    [1] func scale(by factor: Int) {
        width [2] width * factor
        height [3] height * factor
        description = "Scaled size"
    }
}
Drag options to blanks, or click blank then click option'
Amutating
B=
C+=
D*=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '*=' instead of '=' causes incorrect scaling logic here.
Not marking the method as mutating.