Skip to Content
Course content

66: Sendable and Data Race Safety

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've noticed a recurring theme when developers first encounter Swift's strict concurrency checks: there is a pervasive belief that because structs are value types, they are automatically "safe" to move between threads. You'll hear people say, "I'm using a struct, so I don't need to worry about Sendable."

That is a dangerous assumption. Let me show you why.

"Structs are value types, so they're always safe"

class DatabaseConnection {
    var connectionId = UUID()
    func query(_ sql: String) { /* ... */ }
}

struct QueryRequest {
    let sql: String
    let connection: DatabaseConnection // A reference type inside a value type
}

func performQuery() async {
    let connection = DatabaseConnection()
    let request = QueryRequest(sql: "SELECT * FROM users", connection: connection)

    Task {
        // This looks safe because 'request' is a struct, right?
        // Wrong. We just sent a reference to DatabaseConnection across a boundary.
        await request.connection.query(request.sql)
    }
}

In the example above, QueryRequest is indeed a struct. When you pass it into the Task, Swift makes a copy of the struct. But here is the kicker: it only copies the reference to the DatabaseConnection. You now have two different structs in two different threads, both pointing to the exact same instance of DatabaseConnection on the heap. If that class isn't thread-safe, you've just invited a data race into your app, and the compiler is going to scream at you because QueryRequest does not conform to Sendable.

Sendability is recursive, not superficial

For a type to be Sendable, everything it contains must also be Sendable. It's a recursive requirement. A struct is only implicitly Sendable if all of its stored properties are Sendable.

To fix the previous example, we have to ensure the data being moved is actually safe to share. You have a few options here. The most "modern Swift" way is to turn that connection into an actor, or ensure the class is final and contains only immutable (let) properties of Sendable types.

actor DatabaseConnection {
    let connectionId = UUID()
    func query(_ sql: String) { /* ... */ }
}

// Now QueryRequest is implicitly Sendable because 
// String is Sendable and DatabaseConnection (as an actor) is Sendable.
struct QueryRequest {
    let sql: String
    let connection: DatabaseConnection
}

I want you to think of Sendable not as a "capability" you add to a class, but as a guarantee you provide to the compiler. You are promising that this value can be passed across concurrency boundaries without causing a crash or corrupted state.

The @unchecked Sendable escape hatch

Sometimes, you'll deal with legacy code or C-libraries where you know a type is thread-safe (perhaps it uses an internal pthread_mutex or os_unfair_lock), but the Swift compiler can't prove it. In these cases, you can use @unchecked Sendable.

Be careful with this. You are essentially telling the compiler, "Trust me, I know what I'm doing; stop checking this." If you're wrong, you'll get a data race that the compiler can no longer help you find. Use it as a last resort, not a way to make annoying warnings go away.

import Foundation

class LegacyThreadSafeCache: @unchecked Sendable {
    private let lock = NSLock()
    private var storage: [String: Any] = [:]

    func set(_ value: Any, for key: String) {
        lock.lock()
        defer { lock.unlock() }
        storage[key] = value
    }
}

When in doubt, prefer actors or immutable structs. The goal of the Sendable protocol isn't to add boilerplate; it's to move the discovery of concurrency bugs from "random crash in production" to "compile-time error." I'll take a compiler error over a 3:00 AM production page any day.




📋 Practical Task

Fixing the Async Image Metadata Processor

You are working on a photo app. You have a ImageMetadata struct that is intended to be passed from the main UI thread to a background MetadataProcessor actor. However, the code is currently failing to compile because of a Sendable violation.

Your Task: Modify the provided code so that ImageMetadata can be safely passed to the MetadataProcessor. You must ensure the ExifData class is handled correctly to satisfy the compiler's concurrency checks without using @unchecked Sendable.

// --- START OF BROKEN CODE ---
class ExifData {
    var cameraModel: String
    var aperture: Double
    
    init(cameraModel: String, aperture: Double) {
        self.cameraModel = cameraModel
        self.aperture = aperture
    }
}

struct ImageMetadata {
    let fileName: String
    let exif: ExifData
}

actor MetadataProcessor {
    func process(_ metadata: ImageMetadata) async {
        print("Processing \(metadata.fileName) from \(metadata.exif.cameraModel)")
    }
}

func handleImageUpload() async {
    let meta = ImageMetadata(
        fileName: "vacation.jpg", 
        exif: ExifData(cameraModel: "Sony A7III", aperture: 2.8)
    )
    
    let processor = MetadataProcessor()
    await processor.process(meta) // Compiler Error: Non-sendable type 'ImageMetadata' passed across actor boundary
}
// --- END OF BROKEN CODE ---
Rating
0 0

There are no comments for now.

to be the first to leave a comment.