0
0
Swiftprogramming~5 mins

Sendable protocol for thread safety in Swift

Choose your learning style9 modes available
Introduction

The Sendable protocol helps make sure data can be safely shared between different threads without causing problems.

When you want to pass data between different parts of your app running at the same time.
When you use Swift concurrency features like <code>async</code> and <code>await</code>.
When you want to avoid bugs caused by multiple threads changing data at once.
When you create custom types that will be used across threads.
When you want the compiler to help check your code for thread safety.
Syntax
Swift
struct MyData: Sendable {
    var value: Int
}

Types that conform to Sendable promise they can be safely used across threads.

Most simple types like Int, String, and Bool are already Sendable.

Examples
A simple struct with only Sendable properties can conform to Sendable.
Swift
struct User: Sendable {
    let name: String
    let age: Int
}
Use @unchecked Sendable for classes when you promise to handle thread safety yourself.
Swift
class Counter: @unchecked Sendable {
    var count = 0
}
Functions can require parameters to be Sendable to ensure thread safety.
Swift
func updateData(data: some Sendable) async {
    // safe to use data across threads
}
Sample Program

This program defines a Message struct that is Sendable. It then safely sends a message to an async function that prints it.

Swift
import Foundation

struct Message: Sendable {
    let text: String
}

func printMessage(_ message: Message) async {
    print("Message: \(message.text)")
}

@main
struct Main {
    static func main() async {
        let msg = Message(text: "Hello from another thread!")
        await printMessage(msg)
    }
}
OutputSuccess
Important Notes

Marking a type Sendable helps the compiler check your code for thread safety.

Immutable types (ones that don't change) are easier to make Sendable.

Use @unchecked Sendable carefully; it skips safety checks.

Summary

Sendable means data can be safely shared between threads.

Use it with structs and classes to avoid threading bugs.

The compiler helps check your code when you use Sendable.