0
0
Swiftprogramming~3 mins

Why Sendable protocol for thread safety in Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your app could avoid tricky thread bugs automatically with just a simple label?

The Scenario

Imagine you are passing a box of important documents between friends in a busy room. Without clear rules, the box might get dropped or mixed up. In programming, when multiple threads share data, without safety rules, data can get corrupted or cause crashes.

The Problem

Manually ensuring data is safe to share between threads is slow and tricky. You might forget to lock data or accidentally change it while another thread reads it. This leads to bugs that are hard to find and fix.

The Solution

The Sendable protocol in Swift acts like a safety label on data, guaranteeing it can be safely passed between threads. It helps the compiler check your code and prevent unsafe sharing, making your programs more reliable and easier to write.

Before vs After
Before
var sharedData = ["apple", "banana"]
// Manually lock and unlock to avoid thread issues
After
struct FruitList: Sendable {
  var fruits: [String]
}
// Compiler ensures safe sharing automatically
What It Enables

It enables safe and efficient communication between threads without complex manual checks.

Real Life Example

When building an app that fetches data in the background and updates the screen, Sendable ensures the data passed between threads won't cause crashes or weird bugs.

Key Takeaways

Manual thread safety is error-prone and slow.

Sendable protocol marks data as safe to share across threads.

This leads to safer, cleaner, and more reliable concurrent code.