Skip to content

Latest commit

 

History

History
36 lines (28 loc) · 837 Bytes

Protocols.md

File metadata and controls

36 lines (28 loc) · 837 Bytes

Protocols

Protocols are widely used in Swift APIs, but can present unique challenges with concurrency.

Non-isolated Protocol

You have a non-isolated protocol, but need to add conformance to an actor-isolated type.

protocol MyProtocol {
    func doThing(argument: ArgumentType) -> ResultType
}

@MainActor
class MyClass {
}

extension: MyClass: MyProtocol {
    func doThing(argument: ArgumentType) -> ResultType {
    }
}

Solution #1: non-isolated conformance

extension: MyClass: MyProtocol {
    nonisolated func doThing(argument: ArgumentType) -> ResultType {
        // at this point, you likely need to interact with self, so you must satisfy the compiler
        // hazard 1: Availability
        MainActor.assumeIsolated {
            // here you can safely access `self`
        }
    }
}