Section 10/171 menit
10. Isolated Parameters dan `isolated(any)`
10. Isolated Parameters dan isolated(any)
Parameter isolated
Kamu bisa men-declare bahwa fungsi harus dipanggil dengan actor tertentu sebagai isolated context:
swift
actor Counter {
var value = 0
}
func incrementMany(_ counter: isolated Counter, by amount: Int) {
// di sini kita sudah "isolated" ke counter — bisa akses property langsung
counter.value += amount // sync, tanpa await
}
// Caller:
let c = Counter()
await incrementMany(c, by: 10) // await sekali, bukan per akses
Berguna untuk: batch operations. Tanpa isolated, setiap akses property butuh await. Dengan isolated, kamu masuk ke actor sekali, lakukan banyak hal, lalu keluar.
nonisolated(unsafe) (Swift 5.10+) dan Versi Lainnya
nonisolated mengeluarkan sebuah method dari isolation actor. Variannya:
nonisolated— sync, tidak akses isolated state (compiler verifikasi).nonisolated(unsafe)— sama tapi compiler tidak memverifikasi (escape hatch).
swift
actor APIClient {
private let baseURL: URL // immutable
nonisolated let timeout: TimeInterval = 30 // OK: immutable
nonisolated(unsafe) static var debugMode = false // escape hatch
}
isolated(any): Polymorphic Isolation di Closure
Swift 5.9+ memperkenalkan @isolated(any) untuk function/closure yang membawa isolation-nya sendiri:
swift
func runOn(isolation: isolated (any Actor)?, action: () -> Void) {
action() // dijalankan di executor sesuai parameter isolation
}
@MainActor
func main() {
runOn(isolation: MainActor.shared) {
// jalan di main actor
}
}
Use case: helper generic yang harus jalan di executor tertentu yang ditentukan caller. Misalnya: scheduler, dispatcher abstraction.
swift
struct Scheduler {
func schedule<T>(
isolation: isolated (any Actor)? = #isolation,
operation: () async throws -> T
) async rethrows -> T {
try await operation()
}
}
#isolation adalah magic literal yang mengambil isolation context caller — sangat berguna untuk helper yang ingin "menempel" ke isolation pemanggil.