Different ways to create Tasks in Swift concurrency

Viewed 64

When running async code in a non-concurrency context, are these the same things?

Task { ... }

and

Task.init{ ... }

1 Answers

Yes. The .init is redundant, however. This is the common syntax for all initializers. Array(...) is the same as Array.init(...).

Task.init takes a closure, and when there's a single closure parameter, you can drop the parentheses. (This is a form of "trailing closure syntax.") This isn't special for Task.

The full initializer is:

@discardableResult init(priority: TaskPriority? = nil, operation: @escaping @Sendable () async throws -> Success)

priority is optional, so you can drop it. And operation is a closure.

Related