This repository contains Swift playgrounds to explore and understand the new concurrency concepts introduced in Swift. It includes examples of Async/Await, AsyncLet, TaskGroups, and Actors.
Execute 2 asynchronous pieces of work using the Async/Await pattern to showcase the advantages compared to traditional GCD/Operations.
Work that can be done in parallel can use the async let pattern. It is important to note that even though the work is done in parallel, the individual child tasks are awaited in sequence.
Cooperative cancellation. When the 1st child task ends with an error, the parent task will cancel all other child tasks and then throw the error.
Cooperative cancellation. When the 2nd child task ends with an error, the parent task will not cancel the other tasks because it is still awaiting the 1st child task to complete.
Use TaskGroups to avoid the drawback of the async let pattern where parent tasks await child tasks in the order that they appear in code. An error from one of the tasks can set all other tasks to the cancel state and throw the error.
Actors are reference types like classes but do not support inheritance.
Actors prevent data races by creating synchronized access to their isolated data.
Actor race conditions can still occur if used incorrectly, e.g., having 2 points of suspension in common code is not good.
Use of the nonisolated
keyword to tell the compiler that a method is not accessing mutable state.
Main Actor. A Task created from a function having @MainActor
will also inherit the main actor context. A detached task will not.
Feel free to explore the playgrounds in this repository to better understand Swift's concurrency features.