Swift Tasks

Swift uses the Task struct to execute code concurrently. We can run a Task and await the return value or we can use in a “fire and forget” manner. We create a task like this

Task {
   // do something
}

We do not need to call a start method or the likes, once created the code starts. If you intend to return a value you’d write something like this

let result = await Task { () -> String in
   "Hello World"
}.value

Ofcourse we might also have the possibility of throwing an exception, hence we’d use

do {
   let result = try await Task { () -> String in
      throw MyError.failed
   }.value
} catch {
}