0
0
Swiftprogramming~20 mins

Methods in structs in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Struct Methods Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of method modifying struct property
What is the output of this Swift code?
Swift
struct Counter {
    var count = 0
    mutating func increment() {
        count += 1
    }
}

var c = Counter()
c.increment()
print(c.count)
ACompilation error due to missing mutating keyword
B1
C0
DRuntime error
Attempts:
2 left
💡 Hint
Remember that methods that change properties in structs must be marked mutating.
Predict Output
intermediate
2:00remaining
Output of method returning computed value
What does this Swift code print?
Swift
struct Rectangle {
    var width: Int
    var height: Int
    func area() -> Int {
        return width * height
    }
}

let rect = Rectangle(width: 3, height: 4)
print(rect.area())
ARuntime error
B7
CCompilation error: missing return statement
D12
Attempts:
2 left
💡 Hint
The area is width multiplied by height.
🔧 Debug
advanced
2:00remaining
Why does this method cause a compile error?
This Swift struct method tries to modify a property but causes a compile error. Why?
Swift
struct BankAccount {
    var balance: Double = 0.0
    func deposit(amount: Double) {
        balance += amount
    }
}
Adeposit method must return a value
Bbalance is a constant and cannot be changed
CMethod must be marked mutating to modify balance
DStructs cannot have methods that modify properties
Attempts:
2 left
💡 Hint
Think about how structs handle property changes inside methods.
Predict Output
advanced
2:00remaining
Output of method with self reassignment
What is the output of this Swift code?
Swift
struct Point {
    var x: Int
    var y: Int
    mutating func moveToOrigin() {
        self = Point(x: 0, y: 0)
    }
}

var p = Point(x: 5, y: 7)
p.moveToOrigin()
print(p.x, p.y)
A0 0
B5 7
CCompilation error: cannot assign to self
DRuntime error
Attempts:
2 left
💡 Hint
Struct methods can assign a new value to self if marked mutating.
🧠 Conceptual
expert
2:00remaining
Why must methods modifying struct properties be marked mutating?
In Swift, why do methods that change properties of a struct need the mutating keyword?
ABecause structs are value types and mutating methods signal that the method changes the instance itself
BBecause all methods in structs must be mutating by default
CBecause mutating methods run on a separate thread
DBecause mutating methods are only allowed in classes, not structs
Attempts:
2 left
💡 Hint
Think about how value types behave when changed inside methods.