Section 20/202 menit
20. Decision Guide — Memilih Tool yang Tepat
20. Decision Guide — Memilih Tool yang Tepat
Untuk Shared Mutable State
swift
State diakses concurrent dari banyak context?
├── YA → actor (paling natural untuk mutable state)
│ atau Mutex<Value> (jika sync context, tidak bisa await)
└── TIDAK → tidak perlu isolation khusus
Untuk UI Layer
swift
Kode menyentuh UIKit/AppKit?
├── YA → @MainActor
│ Swift 6.2: set default isolation @MainActor per module
└── TIDAK → actor atau nonisolated
Untuk Operasi Concurrent
swift
Jumlah operasi diketahui saat compile time?
├── YA (2-5 operasi) → async let
└── TIDAK (array, dinamis) → withTaskGroup / withThrowingTaskGroup
pertimbangkan limit concurrency
Untuk Streaming Data
swift
Jumlah data: satu nilai atau banyak?
├── Satu nilai → async func dengan return
├── Banyak nilai, finite → Array + async func
└── Banyak nilai, ongoing → AsyncStream / AsyncThrowingStream
Untuk Tipe yang Melintas Isolation
swift
Tipe perlu dikirim antar isolation domain?
├── Value type (struct/enum) dengan all-Sendable properties → Sendable otomatis
├── Reference type (class) → jadikan actor, atau final+immutable+Sendable
├── Non-Sendable yang tidak diakses lagi setelah dikirim → sending modifier
└── Legacy type yang tidak bisa diubah → @unchecked Sendable (hati-hati)
Quick Reference Semua Fitur
| Fitur | Swift | Problem | Gunakan |
|---|---|---|---|
async/await |
5.5 | Callback hell | Semua I/O dan async work |
async let |
5.5 | Sequential async yang bisa parallel | 2-5 op concurrent |
TaskGroup |
5.5 | N concurrent tasks dari collection | Batch processing |
actor |
5.5 | Shared mutable state thread-safety | Data store, cache, service |
@MainActor |
5.5 | UI update thread safety | VC, VM, View |
AsyncStream |
5.5 | Bridge callback ke async | Notification, WebSocket |
| Complete Checking | 6.0 | Data race deteksi | Selalu aktif di Swift 6 |
Sendable |
6.0 | Tipe safe lintas isolation | Semua cross-boundary types |
sending |
6.0 | Transfer non-Sendable type | Ownership transfer |
nonisolated(unsafe) |
6.0 | Opt-out isolation (dangerous) | Hanya dengan justifikasi kuat |
@preconcurrency |
6.0 | Backward compat library | Migrasi saja |
nonisolated stored prop |
6.1 | Overhead await untuk let | Immutable actor properties |
| Improved inference | 6.1 | Terlalu banyak annotation | Kurang annotation manual |
@isolated(any) |
6.1 | Isolation-agnostic callbacks | Framework/library code |
| Default module isolation | 6.2 | Boilerplate @MainActor | UI layer module |
| Task naming | 6.2 | Debug concurrent code | Semua long-running Task |
| async let cancellation | 6.2 | Indeterminate cancellation | Selalu (automatic improvement) |
nonisolated init |
6.2 | Sync object creation | Init dengan hanya let properties |
Dibuat: 2026-05-09 | Swift 5.5 → Swift 6.2 | Comprehensive Concurrency Guide