Bird
Raised Fist0
Swiftprogramming~10 mins

Methods in structs in Swift - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Methods in structs
Define struct with properties
↓
Add method inside struct
↓
Create struct instance
↓
Call method on instance
↓
Method uses properties to compute or act
↓
Return or print result
↓
End
This flow shows how you define a struct with properties and methods, create an instance, call the method, and get the result.
Execution Sample
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())
This code defines a Rectangle struct with width and height, adds a method to calculate area, creates an instance, and prints the area.
Execution Table
StepActionProperties StateMethod CalledMethod ResultOutput
1Define struct Rectanglewidth: -, height: -No--
2Add method area()width: -, height: -No--
3Create instance rectwidth: 3, height: 4No--
4Call rect.area()width: 3, height: 4Yes3 * 4 = 12-
5Print resultwidth: 3, height: 4No1212
6Endwidth: 3, height: 4No--
💡 Method called once, result printed, program ends.
Variable Tracker
VariableStartAfter Step 3After Step 4Final
rect.width-333
rect.height-444
area result--1212
Key Moments - 3 Insights
Why does the method area() use 'width' and 'height' without parameters?
Because methods inside structs can access the struct's own properties directly, as shown in step 4 of the execution_table.
Does calling rect.area() change the properties width or height?
No, the method only reads the properties to calculate area; it does not modify them, as seen in variable_tracker where width and height stay the same.
Why do we need to create an instance before calling the method?
Because methods in structs work on specific instances with their own property values, shown in step 3 creating rect before calling area in step 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 4, what is the method result of rect.area()?
A7
B12
C0
DError
💡 Hint
Check the 'Method Result' column at step 4 in the execution_table.
At which step is the struct instance 'rect' created?
AStep 4
BStep 2
CStep 3
DStep 5
💡 Hint
Look at the 'Action' column in the execution_table for instance creation.
If we change rect.width to 5 before calling area(), what will the method result be at step 4?
A20
B7
C12
DError
💡 Hint
Recall area() returns width * height; changing width to 5 and height is 4 means 5*4.
Concept Snapshot
struct StructName {
  var property1: Type
  var property2: Type
  func methodName() -> ReturnType {
    // use properties to compute or act
  }
}
Create instance: let obj = StructName(...)
Call method: obj.methodName()
Full Transcript
This example shows how to define a struct with properties and a method in Swift. The method can use the struct's properties directly without needing parameters. We create an instance of the struct with specific values, then call the method on that instance. The method calculates and returns a value based on the instance's properties. The execution table traces each step: defining the struct, adding the method, creating an instance, calling the method, and printing the result. The variable tracker shows how the properties and method result change or stay the same. Key moments clarify common confusions about method access to properties, immutability during method calls, and the need for an instance. The quiz tests understanding of method results, instance creation, and effects of changing property values before method calls.

Practice

(1/5)
1.

What is the main purpose of a method inside a Swift struct?

easy
A. To define actions the struct can perform
B. To store data values
C. To create a new struct type
D. To import external libraries

Solution

  1. Step 1: Understand what methods do in structs

    Methods are functions inside structs that define behaviors or actions the struct can perform.
  2. Step 2: Differentiate methods from data storage

    Properties store data, while methods perform actions using that data.
  3. Final Answer:

    To define actions the struct can perform -> Option A
  4. Quick Check:

    Methods = actions in structs [OK]
Hint: Methods = actions inside structs, properties = data [OK]
Common Mistakes:
  • Confusing methods with properties
  • Thinking methods create new types
  • Mixing methods with import statements
2.

Which keyword must be used before a method in a Swift struct if it changes the struct's properties?

easy
A. final
B. override
C. static
D. mutating

Solution

  1. Step 1: Recall Swift's rule for modifying struct properties

    Struct methods that change properties must be marked with mutating to allow modification.
  2. Step 2: Identify the correct keyword

    Among the options, only mutating enables property changes inside struct methods.
  3. Final Answer:

    mutating -> Option D
  4. Quick Check:

    Change properties = mutating [OK]
Hint: Use mutating for methods that change struct properties [OK]
Common Mistakes:
  • Using override in structs (only for classes)
  • Confusing static with mutating
  • Omitting mutating keyword causes errors
3.

What will be the output of this Swift code?

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

var myCounter = Counter()
myCounter.increment()
print(myCounter.count)
medium
A. 0
B. 1
C. Error: Cannot modify property
D. nil

Solution

  1. Step 1: Understand the mutating method increment()

    The method increases count by 1 and is marked mutating, so it can change the property.
  2. Step 2: Trace the code execution

    myCounter starts with count = 0, increment() adds 1, so count becomes 1, then printed.
  3. Final Answer:

    1 -> Option B
  4. Quick Check:

    mutating method changes count to 1 [OK]
Hint: mutating methods can change properties, so count increments [OK]
Common Mistakes:
  • Forgetting mutating causes error
  • Expecting count to stay 0
  • Thinking print outputs nil
4.

Identify the error in this Swift struct method and how to fix it:

struct Score {
    var points = 0
    func addPoint() {
        points += 1
    }
}
medium
A. Method should return points value
B. Property points must be let instead of var
C. Method must be marked mutating to change points
D. No error, code runs fine

Solution

  1. Step 1: Check if method modifies a property

    addPoint() tries to increase points by 1, which modifies the struct's property.
  2. Step 2: Recall Swift rule for modifying properties in structs

    Methods that modify properties must be marked mutating, otherwise compiler error occurs.
  3. Final Answer:

    Method must be marked mutating to change points -> Option C
  4. Quick Check:

    Modify property in struct method = mutating needed [OK]
Hint: Add mutating keyword to methods that change struct properties [OK]
Common Mistakes:
  • Omitting mutating keyword
  • Changing var to let (makes property immutable)
  • Thinking method must return value
5.

Given this struct, which method correctly resets the level property to 1?

struct Game {
    var level = 5

    // Which method resets level to 1?
}
hard
A. mutating func reset() { level = 1 }
B. mutating func reset() -> Int { return 1 }
C. static func reset() { level = 1 }
D. func reset() { level = 1 }

Solution

  1. Step 1: Identify method that changes a property

    Resetting level means changing the property, so method must be mutating.
  2. Step 2: Check each option

    A lacks mutating, so cannot modify property. B is mutating but only returns 1 without changing level. C is static and cannot access instance property. D is mutating and correctly sets level to 1.
  3. Final Answer:

    mutating func reset() { level = 1 } -> Option A
  4. Quick Check:

    Change property in struct method = mutating func [OK]
Hint: Use mutating func to change struct properties inside methods [OK]
Common Mistakes:
  • Forgetting mutating keyword
  • Using static func to access instance properties
  • 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