Question 2Easy
What is the output?
struct P { var x = 1 }
var a = P()
var b = a
b.x = 9
print(a.x)
- 9
- 0
- Compile error
- 1
Answer: D. 1
Explanation
Structs are copied on assignment, so changing b does not affect a.
Step-by-step solution
- P is a struct, so var b = a makes a copy.
- Changing b.x to 9 changes only the copy.
- a.x is still 1 (option D).
Why the other options are wrong
- A. The copy changed, not a; a.x stays 1.
- B. The default value of x is 1, not 0.
- C. The code compiles because a and b are var.
Tip: Struct assignment copies the value; class assignment shares the instance.
Question 4Easy
Which is a value type in Swift?
- class
- closure
- actor reference
- struct
Answer: D. struct
Explanation
Structs and enums are value types, copied on assignment; classes are reference types.
Step-by-step solution
- Structs are value types: assignment makes a copy.
- Classes, actors and closures are reference-based.
- So struct is the value type (option D).
Why the other options are wrong
- A. A class is a reference type.
- B. A closure is a reference-based function value, not a value type in this sense.
- C. An actor is a reference type that serializes access.
Tip: Use struct for plain data; use class when shared identity matters.
Question 8Medium
What is the output?
class C { var x = 1 }
let a = C()
a.x = 7
print(a.x)
- 1
- 7
- Compile error because a is a let
- 0
Answer: B. 7
Explanation
A let reference to a class only fixes the reference; the instance's var properties can still change.
Step-by-step solution
- A is a let reference to a class instance.
- The reference cannot change, but x is a var property of the instance.
- a.x = 7 is allowed, so print shows 7 (option B).
Why the other options are wrong
- A. The property was changed to 7 before printing.
- C. Let only fixes the reference; the instance's var properties can change.
- D. The instance was set to 7, not 0.
Tip: Let on a class fixes the reference, not the object's var properties.
Question 9Hard
When must an enum be declared indirect?
- When it has raw values
- When it has more than 10 cases
- When it conforms to Equatable
- When a case holds another instance of the same enum, like a recursive tree
Answer: D. When a case holds another instance of the same enum, like a recursive tree
Explanation
indirect stores the associated value behind a pointer so recursive enums have finite size.
Step-by-step solution
- A case contains the enum itself.
- Size would be infinite.
- indirect fixes this.
Why the other options are wrong
- A. Raw values don't require indirect.
- B. Number of cases doesn't matter.
- C. Conformance is unrelated.