What is the output of this Swift code snippet?
struct Counter { var count = 0 mutating func increment() { count += 1 } } var c1 = Counter() let c2 = c1 c1.increment() print(c1.count, c2.count)
Remember that structs are value types and copying creates independent instances.
In Swift, structs are value types. When you assign c1 to c2, it copies the value. Incrementing c1 does not affect c2. So c1.count is 1, but c2.count remains 0.
What will be printed by this Swift code?
var name: String? = "Alice" if let unwrappedName = name { print("Hello, \(unwrappedName)!") } else { print("No name provided.") }
Check how optional binding works with if let.
The if let syntax unwraps the optional name safely. Since name contains "Alice", it prints "Hello, Alice!".
Which line in the following Swift code causes a retain cycle leading to a memory leak?
class Person { var name: String var apartment: Apartment? init(name: String) { self.name = name } deinit { print("Person \(name) is being deinitialized") } } class Apartment { var unit: String var tenant: Person? init(unit: String) { self.unit = unit } deinit { print("Apartment \(unit) is being deinitialized") } } var john: Person? = Person(name: "John") var unit4A: Apartment? = Apartment(unit: "4A") john!.apartment = unit4A unit4A!.tenant = john
Think about strong references between classes causing retain cycles.
The line unit4A!.tenant = john creates a strong reference from Apartment to Person. Since Person also strongly references Apartment, this creates a retain cycle. To fix, tenant should be a weak reference.
Choose the correct Swift syntax for declaring a protocol with an associated type named Item.
Recall the keyword for declaring associated types in protocols.
The correct keyword is associatedtype. Option A uses it properly. Option A uses typealias which is invalid here. Option A tries to declare a variable instead of an associated type. Option A tries to assign a default type which is invalid syntax.
Which approach is considered the best practice to safely handle optionals in Swift and avoid runtime crashes?
Think about safety and avoiding crashes.
Using if let or guard let safely unwraps optionals and prevents runtime crashes. Force unwrapping (!) can cause crashes if the optional is nil. Implicitly unwrapped optionals and forced casts are risky and should be avoided unless absolutely sure.