0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Swift Concurrency】Actorとは

0
Last updated at Posted at 2026-02-15

Actorとは

データ競合を防ぐための型。Swift 5.5から導入されたSwift Concurrencyの一部で、並行処理において複数のスレッドから参照されるデータの排他制御を行うことができる仕組み。

使い方

Actorの定義

// classの代わりにactorキーワードを使うだけ
actor Counter {
    private var value = 0

    func increment() {
        // 内部からアクセスするときはawaitは不要
        value += 1
    }

    func getValue() -> Int {
        return value
    }
}
  • actorというキーワードを使って定義を行う。
  • これだけでCounterには排他制御の機能をもった状態になる。つまり、Counterに一度にアクセスできるスレッドは一つに限定される。

Actorの利用

let counter = Counter()

Task {
    // awaitをつけてアクセス
    await counter.increment()
    let newValue = await counter.getValue()
    print("新しい値: \(newValue)")  
}
  • actor内のメンバーにアクセスするにはawaitをつける必要がある。これは、もしCounterが他のタスクからアクセスされていた場合、こちらのタスクは順番待ちになり順番が回ってくるまでサスペンド状態になるため。
  • actorの内部でアクセスするときはawaitは不要。

参考文献

Swift 5.5から登場したActorについて
SwiftのActorを使って安全な並行処理を実装しよう

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?