Challenge - 5 Problems
Swift Methods Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Swift code with a method?
Consider this Swift struct with a method. What will be printed when the code runs?
Swift
struct Counter { var count = 0 mutating func increment() { count += 1 } } var myCounter = Counter() myCounter.increment() print(myCounter.count)
Attempts:
2 left
💡 Hint
Remember that mutating methods can change properties of structs when called on variables.
✗ Incorrect
The method increment() increases count by 1. Since myCounter is a variable (var), calling increment() works and count becomes 1.
❓ Predict Output
intermediate2:00remaining
What does this class method print?
Look at this Swift class with a method. What will be printed when the code runs?
Swift
class Greeter { func greet() { print("Hello, Swift!") } } let greeter = Greeter() greeter.greet()
Attempts:
2 left
💡 Hint
Classes allow methods to be called on instances even if the instance is a constant.
✗ Incorrect
The greet() method prints "Hello, Swift!". Calling it on greeter prints this message.
🔧 Debug
advanced2:00remaining
Why does this Swift code cause a compile error?
This Swift struct has a method that tries to modify a property but causes a compile error. Why?
Swift
struct Point { var x = 0 var y = 0 mutating func moveBy(dx: Int, dy: Int) { x += dx y += dy } }
Attempts:
2 left
💡 Hint
In Swift, methods that change properties of structs must be marked mutating.
✗ Incorrect
The method moveBy tries to change x and y but is not marked mutating, so the compiler disallows it.
❓ Predict Output
advanced2:00remaining
What is the output of this Swift code with a static method?
Look at this Swift class with a static method. What will be printed when the code runs?
Swift
class MathHelper { static func square(_ number: Int) -> Int { return number * number } } print(MathHelper.square(5))
Attempts:
2 left
💡 Hint
Static methods belong to the type itself and can be called without creating an instance.
✗ Incorrect
The static method square returns the number multiplied by itself. Calling square(5) returns 25.
🧠 Conceptual
expert2:00remaining
Which statement about methods in Swift is true?
Choose the correct statement about methods in Swift.
Attempts:
2 left
💡 Hint
Think about how value types like structs behave when methods change their properties.
✗ Incorrect
Mutating methods allow structs and enums to modify their own properties. Classes do not need mutating because they are reference types.