Bird
0
0

The following Swift code tries to modify a property of a struct instance inside a function but causes a compile error:

medium📝 Debug Q14 of 15
iOS Swift - Swift Language Essentials
The following Swift code tries to modify a property of a struct instance inside a function but causes a compile error:
struct Counter {
  var count: Int
}

func increment(counter: Counter) {
  counter.count += 1
}

What is the main reason for the error?
AFunction parameter 'counter' is a constant by default
BStruct properties cannot be modified inside functions
CYou cannot use '+=' operator on Int
DCounter must be a class to modify properties
Step-by-Step Solution
Solution:
  1. Step 1: Understand function parameter mutability

    In Swift, function parameters are constants by default. You cannot modify them inside the function.
  2. Step 2: Analyze the error cause

    The parameter counter is a struct instance passed by value but immutable inside the function. Trying to change counter.count causes a compile error.
  3. Final Answer:

    Function parameter 'counter' is a constant by default -> Option A
  4. Quick Check:

    Function parameters are immutable unless marked inout [OK]
Quick Trick: Function parameters are constants unless 'inout' is used [OK]
Common Mistakes:
  • Thinking structs can't have mutable properties
  • Believing '+=' is invalid for Int
  • Assuming classes are required for mutation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes