0
0
Swiftprogramming~5 mins

Actor declaration syntax in Swift

Choose your learning style9 modes available
Introduction

Actors help keep your program safe when many parts try to change data at the same time. They make sure only one part can change data at once.

When you want to protect data from being changed by many parts of your program at the same time.
When you write code that works with tasks running at the same time and need to avoid mistakes.
When you want to organize code that manages shared information safely.
When you want to use Swift's built-in way to handle safe data access in concurrent programs.
Syntax
Swift
actor ActorName {
    // properties and methods
}

The keyword actor declares a special type that protects its data.

Inside the actor, you write properties and methods like in a class.

Examples
This actor keeps a number and can increase it safely.
Swift
actor Counter {
    var value = 0

    func increment() {
        value += 1
    }
}
This actor manages money safely, allowing deposits and withdrawals.
Swift
actor BankAccount {
    var balance: Double = 0.0

    func deposit(amount: Double) {
        balance += amount
    }

    func withdraw(amount: Double) -> Bool {
        if balance >= amount {
            balance -= amount
            return true
        } else {
            return false
        }
    }
}
Sample Program

This program creates an actor that stores temperature. It safely updates and reads the temperature using async calls.

Swift
import Foundation

actor TemperatureSensor {
    var temperature: Double = 20.0

    func updateTemperature(to newTemp: Double) {
        temperature = newTemp
    }

    func readTemperature() -> Double {
        return temperature
    }
}

@main
struct Main {
    static func main() async {
        let sensor = TemperatureSensor()
        await sensor.updateTemperature(to: 25.5)
        let currentTemp = await sensor.readTemperature()
        print("Current temperature is \(currentTemp)°C")
    }
}
OutputSuccess
Important Notes

Actors use await when calling their methods because they work asynchronously.

Actors help avoid problems when many parts of your program try to change data at the same time.

Summary

Actors are special types that protect data in concurrent programs.

Use the actor keyword to declare them.

Call actor methods with await to safely access or change data.