Section 4/161 menit

4. Strict Concurrency Checking & Swift 6

4. Strict Concurrency Checking & Swift 6

Level Concurrency Checking

swift
// Package.swift — mengaktifkan strict concurrency
targets: [
    .target(
        name: "MyApp",
        swiftSettings: [
            // Level 1: minimal (default Swift 5)
            // Hanya flag penggunaan @Sendable closure yang salah
            .enableUpcomingFeature("StrictConcurrency"),
            
            // Level 2: targeted — periksa annotation yang ada
            // Perhatikan annotation @Sendable, actor, yang sudah ada
            
            // Level 3: complete — semua pelanggaran dilaporkan
            // Setara dengan Swift 6 mode
            .unsafeFlags(["-strict-concurrency=complete"])
        ]
    )
]
swift
# Aktifkan via command line
swift build -Xswiftc -strict-concurrency=complete
swift build -Xswiftc -warn-concurrency  # Swift 5 compat

# Di Swift 6 mode (default error, bukan warning)
swift build -swift-version 6

Diagnosis Warning yang Umum

swift
// Warning 1: Sending non-Sendable value
class NetworkService { }  // non-Sendable class

func fetchData() async {
    let service = NetworkService()
    await Task {
        service.fetch()  // ⚠️ Sending 'service' risks causing data races
    }.value
}

// Warning 2: Main actor-isolated property referenced from non-isolated context
@MainActor
class AppState {
    var username: String = ""
}

func updateUsername(state: AppState) {
    // ⚠️ Main actor-isolated property 'username' cannot be accessed from non-isolated
    print(state.username)
}

// Warning 3: Immutable property of non-Sendable type
class Container {
    let items: [NonSendableItem]  // let, tapi type-nya non-Sendable
}
// Container sendiri menjadi non-Sendable