ConcurrencyMidMCQ
What is `Sendable` and why does it matter?
Test your knowledge:
Explanation & Code
Answer:
Sendable is a protocol that marks a type as safe to share across concurrency domains (actors, tasks). The compiler enforces this to prevent data races at compile time.
Code Example:
// Structs with Sendable properties are automatically Sendable
struct UserProfile: Sendable {
let id: Int
let name: String
}
// Classes need to be carefully marked — only if truly thread-safe
final class ImmutableConfig: Sendable {
let apiKey: String
init(apiKey: String) { self.apiKey = apiKey }
}
// Actor — implicitly Sendable
actor DataCache {
var items: [String: Data] = [:]
}
// ⚠️ This causes a compiler error — non-Sendable type crossing actor boundary
class NonSendableData { var value = 0 }
actor MyActor {
func process(_ data: NonSendableData) { } // ❌ compiler warning
}
Rate your understanding: