Browse Questions
- AsyncStream converts callback or delegate-based event sources into an AsyncSequence you can iterate over with for await.
- Use Secure Message when two parties with separate key pairs exchange data, and Secure Cell when a single party encrypts data for itself.
- An actor is a reference type that protects its mutable state from concurrent access.
- some declares an opaque return type — the function returns a specific concrete type that conforms to a protocol, but the caller doesn't need to know which type it is.
Answer:
An actor is a reference type that protects its mutable state from concurrent access. The Swift compiler enforces that only one task accesses the actor's internals at a time.
Code Example:
actor ImageCache {
private var cache: [URL: UIImage] = [:]
func image(for url: URL) -> UIImage? {
cache[url]
}
func store(_ image: UIImage, for url: URL) {
cache[url] = image
}
}
// Usage — must be awaited from outside the actor
let cache = ImageCache()
let img = await cache.image(for: url)
await cache.store(image, for: url)
Key Points:
- Use
actorfor shared mutable state accessed from multiple tasks @MainActoris a global actor that ensures code runs on the main thread- Actor methods are automatically
asyncwhen called from outside