Bird
Raised Fist0
Swiftprogramming~20 mins

Sendable protocol for thread safety in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift Sendable Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Swift code using Sendable?

Consider this Swift code snippet using the Sendable protocol. What will be printed?

Swift
import Foundation

struct Counter: Sendable {
    var value: Int
    mutating func increment() {
        value += 1
    }
}

func updateCounter(counter: inout Counter) {
    counter.increment()
}

var myCounter = Counter(value: 0)
updateCounter(counter: &myCounter)
print(myCounter.value)
A1
B0
CCompilation error due to Sendable conformance
DRuntime error due to thread safety violation
Attempts:
2 left
💡 Hint

Think about what Sendable means for value types and how mutation affects the value.

🧠 Conceptual
intermediate
1:30remaining
Which type automatically conforms to Sendable in Swift?

Which of the following Swift types automatically conform to the Sendable protocol without extra code?

AEnums with associated reference types
BClosures capturing mutable state
CClasses with mutable properties
DStructs with only stored properties that are Sendable
Attempts:
2 left
💡 Hint

Think about value types and their stored properties.

🔧 Debug
advanced
2:00remaining
What error does this code raise related to Sendable?

Examine this Swift code snippet. What error will the compiler produce?

Swift
import Foundation

class DataHolder {
    var data: String
    init(data: String) {
        self.data = data
    }
}

struct Container: Sendable {
    var holder: DataHolder
}
ANo error, code compiles successfully
BRuntime error due to data race
CType 'DataHolder' does not conform to 'Sendable'
DMissing initializer error
Attempts:
2 left
💡 Hint

Check if classes conform to Sendable automatically.

📝 Syntax
advanced
1:30remaining
Which option correctly declares a Sendable class in Swift?

Which of the following Swift class declarations correctly conforms to Sendable?

Aclass UnsafeClass: Sendable {}
Bfinal class SafeClass: Sendable {}
Cfinal class SafeClass: Sendable { var value: Int }
Dclass SafeClass: Sendable { let value: Int }
Attempts:
2 left
💡 Hint

Consider what makes a class conform to Sendable safely.

🚀 Application
expert
3:00remaining
How many items are in the dictionary after this concurrent Sendable code runs?

Given this Swift code using concurrency and Sendable, how many items will the dictionary contain after execution?

Swift
import Foundation

@Sendable
func addItem(to dict: inout [Int: String], key: Int, value: String) {
    dict[key] = value
}

var sharedDict = [Int: String]()

let queue = DispatchQueue(label: "concurrent", attributes: .concurrent)

for i in 0..<5 {
    queue.async(flags: .barrier) {
        addItem(to: &sharedDict, key: i, value: "Item \(i)")
    }
}

queue.sync(flags: .barrier) {}

print(sharedDict.count)
A5
B0
CLess than 5 due to race conditions
DCompilation error due to Sendable misuse
Attempts:
2 left
💡 Hint

Consider how the barrier flag affects concurrent writes.

Practice

(1/5)
1. What does the Sendable protocol in Swift ensure?
easy
A. That a function runs asynchronously.
B. That a class can only be used on the main thread.
C. That a variable is immutable.
D. That data can be safely shared between threads without causing race conditions.

Solution

  1. Step 1: Understand the purpose of Sendable

    The Sendable protocol marks types that can be safely passed between threads without causing data races.
  2. Step 2: Compare options with the definition

    Only That data can be safely shared between threads without causing race conditions. correctly describes this safety guarantee. Other options describe unrelated concepts.
  3. Final Answer:

    That data can be safely shared between threads without causing race conditions. -> Option D
  4. Quick Check:

    Sendable = safe cross-thread data sharing [OK]
Hint: Sendable means safe to share data across threads [OK]
Common Mistakes:
  • Confusing Sendable with immutability
  • Thinking Sendable restricts to main thread only
  • Assuming Sendable makes functions async
2. Which of the following is the correct way to declare a struct as Sendable in Swift?
easy
A. struct Data { var value: Int } implements Sendable
B. struct Data: Sendable { var value: Int }
C. struct Data Sendable { var value: Int }
D. struct Data { var value: Int } : Sendable

Solution

  1. Step 1: Recall Swift protocol conformance syntax

    In Swift, a type conforms to a protocol by listing it after a colon following the type name.
  2. Step 2: Match syntax to options

    struct Data: Sendable { var value: Int } uses correct syntax: struct Data: Sendable { ... }. Others are invalid Swift syntax.
  3. Final Answer:

    struct Data: Sendable { var value: Int } -> Option B
  4. Quick Check:

    Protocol conformance uses colon after type name [OK]
Hint: Use colon after struct name to conform to Sendable [OK]
Common Mistakes:
  • Placing protocol after braces
  • Using 'implements' keyword (not Swift)
  • Omitting colon between type and protocol
3. What will happen when you try to compile this Swift code?
struct Counter: Sendable {
  var count: Int
}

let counter = Counter(count: 5)
Task {
  print(counter.count)
}
medium
A. It compiles and prints 5.
B. It causes a compile-time error because Counter is not Sendable.
C. It causes a runtime error due to thread safety violation.
D. It compiles but prints 0.

Solution

  1. Step 1: Check if Counter conforms to Sendable

    The struct explicitly conforms to Sendable and contains only an Int, which is Sendable.
  2. Step 2: Understand Task usage

    The Task runs asynchronously but can safely access counter because it is Sendable.
  3. Final Answer:

    It compiles and prints 5. -> Option A
  4. Quick Check:

    Sendable struct with Int prints value safely [OK]
Hint: Sendable structs with simple types compile and run safely [OK]
Common Mistakes:
  • Assuming compile error without checking conformance
  • Confusing runtime errors with compile errors
  • Thinking default structs are not Sendable
4. Identify the error in this Swift code using Sendable:
class DataHolder: Sendable {
  var data: [Int]
  init(data: [Int]) {
    self.data = data
  }
}
medium
A. Missing explicit Sendable conformance on Array.
B. Class cannot conform to Sendable at all.
C. Array<Int> is not Sendable by default, causing a compile error.
D. No error; code compiles fine.

Solution

  1. Step 1: Check Sendable conformance for class with mutable property

    Classes with mutable stored properties like arrays are not automatically Sendable.
  2. Step 2: Understand why Array<Int> is not Sendable by default

    Array is a reference type and mutable, so compiler disallows automatic Sendable conformance without extra guarantees.
  3. Final Answer:

    Array<Int> is not Sendable by default, causing a compile error. -> Option C
  4. Quick Check:

    Mutable reference types block Sendable conformance [OK]
Hint: Mutable class properties like arrays block Sendable by default [OK]
Common Mistakes:
  • Thinking classes cannot conform to Sendable at all
  • Assuming arrays are always Sendable
  • Ignoring mutability in Sendable checks
5. You want to make this struct safely shareable across threads. What is the best way to fix it?
struct UserData: Sendable {
  var name: String
  var preferences: [String: String]
}
hard
A. Make preferences an immutable dictionary and ensure keys and values are Sendable.
B. Remove Sendable conformance because dictionaries are never Sendable.
C. Change preferences to a class type and mark it as Sendable.
D. Add @Sendable attribute to the struct.

Solution

  1. Step 1: Understand Sendable requirements for dictionary properties

    Dictionaries are Sendable only if their keys and values are Sendable and the dictionary is used immutably.
  2. Step 2: Apply immutability and ensure key/value types conform

    Making preferences immutable (let) and using Sendable key/value types (String) satisfies Sendable.
  3. Final Answer:

    Make preferences an immutable dictionary and ensure keys and values are Sendable. -> Option A
  4. Quick Check:

    Immutable dictionary with Sendable types = Sendable struct [OK]
Hint: Use immutable dictionary with Sendable keys/values for Sendable struct [OK]
Common Mistakes:
  • Thinking dictionaries are never Sendable
  • Confusing @Sendable attribute with Sendable protocol
  • Using mutable properties in Sendable structs
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard