Consider this Swift struct with a mutating method that changes a property. What will be printed?
struct Counter { var count = 0 mutating func increment() { count += 1 } } var myCounter = Counter() myCounter.increment() print(myCounter.count)
Remember that mutating methods can change properties only if the instance is a variable.
The increment() method is marked mutating, so it can modify count. Since myCounter is a variable (var), calling increment() increases count from 0 to 1. Thus, printing myCounter.count outputs 1.
What happens if you call a mutating method on a constant instance of a struct?
struct Point { var x = 0 var y = 0 mutating func moveBy(dx: Int, dy: Int) { x += dx y += dy } } let fixedPoint = Point() fixedPoint.moveBy(dx: 5, dy: 5)
Think about whether a constant struct instance can be changed.
In Swift, structs are value types. A let constant instance cannot be modified. Calling a mutating method tries to change the instance, which is not allowed on constants. This causes a compile-time error.
Identify the reason for the compile error in this Swift code.
struct Rectangle { var width: Int var height: Int func doubleSize() { width *= 2 height *= 2 } } var rect = Rectangle(width: 3, height: 4) rect.doubleSize()
Check if the method that changes properties is marked correctly.
The method doubleSize() tries to modify width and height, but it is not marked mutating. In Swift, only mutating methods can change properties of value types like structs. This causes a compile error.
Choose the correct syntax for a mutating method that increments a value.
The mutating keyword goes before func.
In Swift, the correct syntax to declare a mutating method is mutating func methodName() { }. Option D follows this syntax. Other options have incorrect keyword order or wrong keywords.
Given this Swift struct and code, what is the value of game.score after calling increaseScore() twice?
struct Game { var score = 0 mutating func increaseScore() { score += 10 } } var game = Game() game.increaseScore() game.increaseScore()
Each call adds 10 to score. How many calls are made?
The increaseScore() method adds 10 to score. It is called twice on a variable instance game. So, score becomes 0 + 10 + 10 = 20.