0
0
Swiftprogramming~20 mins

Adding methods in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Methods Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
ACompilation error: cannot use mutating method on variable
B1
C0
DRuntime error
Attempts:
2 left
💡 Hint
Remember that mutating methods can change properties of structs when called on variables.
Predict Output
intermediate
2: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()
ACompilation error: cannot call method on constant
BNo output
CRuntime error: method not found
DHello, Swift!
Attempts:
2 left
💡 Hint
Classes allow methods to be called on instances even if the instance is a constant.
🔧 Debug
advanced
2: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
    }
}
ABecause moveBy is not marked as mutating, so it cannot change properties
BBecause x and y are constants and cannot be changed
CBecause structs cannot have methods
DBecause dx and dy parameters are constants
Attempts:
2 left
💡 Hint
In Swift, methods that change properties of structs must be marked mutating.
Predict Output
advanced
2: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))
ACompilation error: cannot call static method like this
B5
C25
DRuntime error
Attempts:
2 left
💡 Hint
Static methods belong to the type itself and can be called without creating an instance.
🧠 Conceptual
expert
2:00remaining
Which statement about methods in Swift is true?
Choose the correct statement about methods in Swift.
AMutating methods can modify properties of value types like structs and enums
BInstance methods cannot access properties of the instance
CStatic methods can only be called on instances, not on the type itself
DOnly classes can have methods; structs and enums cannot
Attempts:
2 left
💡 Hint
Think about how value types like structs behave when methods change their properties.