Consider the following Swift code where an array is copied and modified. What will be printed?
var original = [1, 2, 3] var copy = original copy.append(4) print(original.count)
Think about whether arrays in Swift share storage or copy on write.
Arrays in Swift are value types. When you assign original to copy, a new copy is made. Modifying copy does not affect original. So original.count remains 3.
Which reason best explains why Swift collections like Array and Dictionary are value types?
Think about what problems shared mutable state can cause in concurrent code.
Value types prevent multiple parts of code from changing the same data at once, which helps avoid bugs in concurrent programming. Swift collections use copy-on-write to be efficient but still safe.
Given this Swift code, what error will the compiler show?
let numbers = [1, 2, 3] numbers.append(4)
Think about whether you can change a value type declared with let.
Arrays are value types. Declaring with let makes the array immutable. Trying to append causes a compile-time error because you cannot mutate a constant.
Examine this Swift code. What will be printed?
var dict1 = ["a": 1, "b": 2] var dict2 = dict1 dict2["a"] = 10 print(dict1["a"] ?? 0)
Remember how value types behave when copied and modified.
Dictionaries in Swift are value types. Changing dict2 does not affect dict1. So dict1["a"] remains 1.
Swift collections are value types but can be large. How does Swift avoid performance problems when copying them?
Think about how Swift balances safety and speed with value types.
Swift collections use copy-on-write. They share storage until one copy changes, then a real copy is made. This keeps performance good while preserving value semantics.