Consider this Swift code snippet using the Sendable protocol. What will be printed?
import Foundation struct Counter: Sendable { var value: Int mutating func increment() { value += 1 } } func updateCounter(counter: inout Counter) { counter.increment() } var myCounter = Counter(value: 0) updateCounter(counter: &myCounter) print(myCounter.value)
Think about what Sendable means for value types and how mutation affects the value.
The struct Counter conforms to Sendable, meaning it can be safely used across concurrency domains. The increment() method increases value by 1. After calling updateCounter, myCounter.value becomes 1.
Which of the following Swift types automatically conform to the Sendable protocol without extra code?
Think about value types and their stored properties.
Structs whose stored properties all conform to Sendable automatically conform to Sendable. Classes and closures capturing mutable state do not automatically conform.
Examine this Swift code snippet. What error will the compiler produce?
import Foundation class DataHolder { var data: String init(data: String) { self.data = data } } struct Container: Sendable { var holder: DataHolder }
Check if classes conform to Sendable automatically.
Classes do not automatically conform to Sendable. Since Container has a stored property of class type DataHolder which is not Sendable, the compiler raises a conformance error.
Which of the following Swift class declarations correctly conforms to Sendable?
Consider what makes a class conform to Sendable safely.
Only final classes without mutable shared state can conform to Sendable safely. Option B declares a final class with no stored properties, so it conforms. Other options either lack final or have mutable properties without synchronization.
Given this Swift code using concurrency and Sendable, how many items will the dictionary contain after execution?
import Foundation @Sendable func addItem(to dict: inout [Int: String], key: Int, value: String) { dict[key] = value } var sharedDict = [Int: String]() let queue = DispatchQueue(label: "concurrent", attributes: .concurrent) for i in 0..<5 { queue.async(flags: .barrier) { addItem(to: &sharedDict, key: i, value: "Item \(i)") } } queue.sync(flags: .barrier) {} print(sharedDict.count)
Consider how the barrier flag affects concurrent writes.
The barrier flag ensures that each write to sharedDict happens exclusively, preventing race conditions. Therefore, all 5 items are added, and the dictionary count is 5.