Consider this Swift code using a struct. What will be printed?
struct Point { var x: Int var y: Int } var p1 = Point(x: 5, y: 10) var p2 = p1 p2.x = 20 print(p1.x, p2.x)
Remember that structs are value types and are copied when assigned.
When p2 is assigned from p1, it creates a copy. Changing p2.x does not affect p1.x. So p1.x remains 5, p2.x becomes 20.
Look at this Swift code. What is the value of a.count after execution?
struct Counter { var count: Int } var a = Counter(count: 1) var b = a b.count += 1
Think about whether a and b share the same data or not.
Since Counter is a struct, b is a copy of a. Modifying b.count does not change a.count. So a.count remains 1 (while b.count becomes 2).
Examine this Swift code. Why do the two print statements output different values?
struct Score { var points: Int } var s1 = Score(points: 10) var s2 = s1 s2.points = 20 print(s1.points) print(s2.points)
Recall how structs behave when assigned to new variables.
Structs in Swift are value types, so assigning s1 to s2 copies the data. Changing s2.points does not affect s1.points. Therefore, s1.points prints 10, s2.points prints 20.
Given this struct, which code snippet will cause a compile-time error?
struct Person { var name: String var age: Int } let p1 = Person(name: "Alice", age: 30) var p2 = p1
Consider mutability of struct instances and their properties.
p1 is a let constant, so its properties cannot be mutated. p1.name.append(" Smith") calls a mutating method on p1.name, which is not allowed and causes a compile-time error.
The other options only affect the mutable p2.
Consider this Swift code using structs and arrays. How many elements does arr2 contain after execution?
struct Item { var id: Int } var arr1 = [Item(id: 1), Item(id: 2)] var arr2 = arr1 arr2.append(Item(id: 3))
Think about how arrays and structs behave when assigned and modified.
Arrays in Swift are value types (structs). Assigning arr1 to arr2 copies the array. Appending to arr2 does not affect arr1. So arr2 has 3 elements, arr1 remains with 2.