Bird
Raised Fist0
Swiftprogramming~20 mins

Adding methods in Swift - Practice Problems & Coding Challenges

Choose your learning style10 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.

Practice

(1/5)
1.

What is the main purpose of adding methods to a struct or class in Swift?

easy
A. To store more data inside the type
B. To make the type immutable
C. To change the type to a different type
D. To add actions or behaviors related to the data inside the type

Solution

  1. Step 1: Understand what methods do

    Methods are functions inside a struct or class that perform actions related to that type's data.
  2. Step 2: Identify the purpose of methods

    Methods organize code by grouping behaviors with the data they act on, making code reusable and clear.
  3. Final Answer:

    To add actions or behaviors related to the data inside the type -> Option D
  4. Quick Check:

    Methods = actions on data [OK]
Hint: Methods are functions inside types that do things with data [OK]
Common Mistakes:
  • Thinking methods only store data
  • Confusing methods with properties
  • Believing methods change the type itself
2.

Which of the following is the correct way to define a method named greet inside a Swift struct?

struct Person {
    // Your method here
}
easy
A. function greet() { print("Hello") }
B. method greet() { print("Hello") }
C. func greet() { print("Hello") }
D. def greet() { print("Hello") }

Solution

  1. Step 1: Recall Swift method syntax

    In Swift, methods inside structs or classes use the keyword func followed by the method name and parentheses.
  2. Step 2: Check each option

    func greet() { print("Hello") } uses func greet(), which is correct. The other options use incorrect keywords not valid in Swift.
  3. Final Answer:

    func greet() { print("Hello") } -> Option C
  4. Quick Check:

    Swift methods start with func [OK]
Hint: Use 'func' keyword to define methods in Swift [OK]
Common Mistakes:
  • Using 'method', 'def', or 'function' instead of 'func'
  • Missing parentheses after method name
  • Not placing method inside struct or class
3.

What will be the output of the following Swift code?

struct Counter {
    var count = 0
    mutating func increment() {
        count += 1
    }
}

var c = Counter()
c.increment()
print(c.count)
medium
A. 1
B. Error: Cannot mutate property in method
C. 0
D. nil

Solution

  1. Step 1: Understand the struct and method

    The struct has a variable count starting at 0. The method increment adds 1 to count. It is marked mutating to allow changing the struct's data.
  2. Step 2: Trace the code execution

    We create c as a Counter instance with count = 0. Calling c.increment() increases count to 1. Printing c.count outputs 1.
  3. Final Answer:

    1 -> Option A
  4. Quick Check:

    Mutating method changes count from 0 to 1 [OK]
Hint: Mutating methods can change struct properties [OK]
Common Mistakes:
  • Forgetting 'mutating' keyword causes error
  • Expecting count to stay 0 after increment
  • Confusing structs with classes (no mutating needed)
4.

Identify the error in this Swift code and choose the fix:

struct BankAccount {
    var balance: Double = 0.0
    func deposit(amount: Double) {
        balance += amount
    }
}
medium
A. Add mutating before func deposit
B. Change var balance to let balance
C. Remove amount parameter from deposit method
D. Change func to static func

Solution

  1. Step 1: Understand the error cause

    The method deposit tries to change balance, a property of the struct. In Swift, methods that modify struct properties must be marked mutating.
  2. Step 2: Identify the fix

    Adding mutating before func deposit allows the method to modify balance. Other options do not fix the mutation error.
  3. Final Answer:

    Add mutating before func deposit -> Option A
  4. Quick Check:

    Mutating keyword needed to change struct properties [OK]
Hint: Use 'mutating' for methods that change struct properties [OK]
Common Mistakes:
  • Omitting 'mutating' keyword causes compile error
  • Changing var to let prevents modification
  • Misusing static keyword for instance methods
5.

You want to add a method reset() to this Swift struct that sets count back to zero. Which is the correct way to do this?

struct Counter {
    var count: Int
    // Add reset method here
}
hard
A. func reset() { count = 0 }
B. mutating func reset() { count = 0 }
C. static func reset() { count = 0 }
D. func reset() -> Int { return 0 }

Solution

  1. Step 1: Understand method purpose and struct rules

    The method reset() must change the property count. Since Counter is a struct, methods that modify properties must be marked mutating.
  2. Step 2: Evaluate options

    mutating func reset() { count = 0 } correctly uses mutating func reset() and sets count = 0. func reset() { count = 0 } lacks mutating, causing error. static func reset() { count = 0 } is static and cannot access instance property. func reset() -> Int { return 0 } returns 0 but does not change count.
  3. Final Answer:

    mutating func reset() { count = 0 } -> Option B
  4. Quick Check:

    Mutating method needed to reset struct property [OK]
Hint: Mutating methods change struct properties like resetting count [OK]
Common Mistakes:
  • Forgetting 'mutating' keyword causes error
  • Using static method cannot access instance data
  • Returning value instead of changing property
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard