0
0
Swiftprogramming~30 mins

Sendable protocol for thread safety in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the Sendable Protocol for Thread Safety in Swift
📖 Scenario: You are building a simple Swift program that shares data safely between threads. Swift's Sendable protocol helps ensure data can be passed between threads without causing problems.
🎯 Goal: Learn how to mark a custom struct as Sendable and use it safely across threads.
📋 What You'll Learn
Create a struct called Message with a text property of type String
Make Message conform to the Sendable protocol
Create a constant message of type Message with the text "Hello from thread!"
Use DispatchQueue.global().async to print the message.text safely from a background thread
💡 Why This Matters
🌍 Real World
In real apps, data often moves between threads. Marking data as Sendable helps prevent bugs and crashes when sharing data safely.
💼 Career
Understanding Sendable is important for Swift developers working on apps that use concurrency, such as iOS apps with background tasks.
Progress0 / 4 steps
1
Create the Message struct
Create a struct called Message with a single property text of type String.
Swift
Need a hint?

Use struct Message { let text: String } to create the struct.

2
Make Message conform to Sendable
Make the Message struct conform to the Sendable protocol by adding : Sendable after the struct name.
Swift
Need a hint?

Add : Sendable right after Message in the struct declaration.

3
Create a Message instance
Create a constant called message of type Message with the text exactly set to "Hello from thread!".
Swift
Need a hint?

Use let message = Message(text: "Hello from thread!") to create the instance.

4
Print message.text safely from a background thread
Use DispatchQueue.global().async to print message.text from a background thread.
Swift
Need a hint?

Use DispatchQueue.global().async { print(message.text) } to print safely on a background thread.