Swift 6 cheatsheet
Swift 6: Errors and concurrency
6 common Swift 6 tasks.
Throw and catch errors
Mark functions that can fail with throws, call them with try, and handle errors in do/catch.
enum ValidationError: Error { case empty }
func validate(_ text: String) throws {
if text.isEmpty { throw ValidationError.empty }
}
do {
try validate("")
} catch {
print("failed: \(error)")
}
Async functions
async functions can suspend. Call them with await.
func fetchUser() async throws -> User {
let (data, _) = try await URLSession.shared.data(from: url)
return try JSONDecoder().decode(User.self, from: data)
}
Run work in parallel
async let starts child tasks that run concurrently.
async let first = fetchUser()
async let second = fetchPosts()
let (user, posts) = try await (first, second)
Start a task
Task starts asynchronous work from synchronous code.
Task {
let user = try await fetchUser()
print(user.name)
}
Protect shared state with an actor
An actor processes one call at a time, which prevents data races. Call its methods with await.
actor Counter {
private var value = 0
func increment() -> Int {
value += 1
return value
}
}
let count = await counter.increment()
Update the UI on the main actor
Mark UI code @MainActor so it always runs on the main thread.
@MainActor
final class ViewModel: ObservableObject {
@Published var items: [String] = []
}