0
0
Swiftprogramming~5 mins

Why actors prevent data races in Swift

Choose your learning style9 modes available
Introduction

Actors help keep your program safe by making sure only one part changes data at a time. This stops mistakes called data races.

When you have multiple parts of your program trying to change the same data at once.
When you want to avoid confusing bugs caused by data changing unexpectedly.
When you want your program to run smoothly without crashes from data conflicts.
When you want to write safe code that is easier to understand and maintain.
Syntax
Swift
actor MyActor {
    var count = 0

    func increment() async {
        count += 1
    }
}

An actor is like a special box that only lets one person inside at a time.

Functions inside an actor run one by one, so data inside is safe.

Examples
This actor safely changes value one at a time.
Swift
actor Counter {
    var value = 0

    func addOne() async {
        value += 1
    }
}
You use await to call actor functions because they run safely one after another.
Swift
let counter = Counter()

Task {
    await counter.addOne()
}
Sample Program

This program uses an actor to safely increase and read a number. The actor makes sure only one change happens at a time, so the number is always correct.

Swift
import Foundation

actor SafeCounter {
    var count = 0

    func increment() async {
        count += 1
    }

    func getCount() async -> Int {
        return count
    }
}

let counter = SafeCounter()

Task {
    await counter.increment()
    let current = await counter.getCount()
    print("Count is now \(current)")
}

// Wait a moment to let the Task finish
Thread.sleep(forTimeInterval: 1)
OutputSuccess
Important Notes

Actors protect data by allowing only one task to access their data at a time.

You must use await when calling actor methods because they might pause to wait their turn.

Actors help avoid bugs that happen when many parts try to change data at once.

Summary

Actors keep data safe by letting only one task change it at a time.

This prevents data races, which are bugs from simultaneous data changes.

Use await to call actor methods because they run in order.