Section 7/201 menit

7. Sendable Enforcement

7. Sendable Enforcement

Teori: Type System sebagai Safety Boundary

Sendable enforcement adalah konsekuensi dari Complete Concurrency Checking. Setiap nilai yang melintas isolation boundary harus bisa dibuktikan aman oleh compiler.

Lihat file swift-isolation-swift6.md untuk teori mendalam tentang Sendable. Di sini fokus pada enforcement behavior di Swift 6:

swift
// Swift 5: warning (bisa diabaikan)
class NonSendableConfig {
    var timeout = 30
}

actor Service {
    func configure(with config: NonSendableConfig) { }  // warning saja
}

// Swift 6: ERROR (tidak bisa dikompilasi)
// error: sending 'config' risks causing data races
// Non-Sendable type cannot cross isolation boundary

Pattern Fix yang Umum

swift
// Pattern 1: struct (paling sederhana)
struct Config: Sendable {
    var timeout: Int = 30
    var retries: Int = 3
}

// Pattern 2: final class dengan immutable properties
final class Config: Sendable {
    let timeout: Int
    let retries: Int
    init(timeout: Int = 30, retries: Int = 3) {
        self.timeout = timeout
        self.retries = retries
    }
}

// Pattern 3: jadikan bagian dari actor
actor Service {
    var timeout: Int = 30
    var retries: Int = 3
    // Config tidak perlu dikirim — sudah ada di dalam actor
}

// Pattern 4: @unchecked Sendable (last resort)
final class Config: @unchecked Sendable {
    private let lock = NSLock()
    private var _timeout = 30
    var timeout: Int {
        get { lock.withLock { _timeout } }
        set { lock.withLock { _timeout = newValue } }
    }
}