Vincent Tourraine
Blog

Notes WWDC 2021 : What’s new in Swift

#dev

Mes notes pour la session What’s new in Swift de la WWDC 2021.

Swift packages

Swift package collections

New open source packages

Complement what’s available in standard library:

Swift on server

Developer experience improvements

Ergonomic improvements

Asynchronous and concurrent programming

Async example:

func fetchImage(id: String) async throws -> UIImage {
  let request = self.imageURLRequest(for: id)
  let (data, response) = try await URLSession.shared.data(for: request)
  if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode != 200 {
    throw TransferFailure()
  }
  guard let image = UIImage(data: data) else {
    throw ImageDecodingFailure()
  }
  return image
}

Structured concurrency example:

func titleImage() async throws -> Image {
  async let background = renderBackground()
  async let foreground = renderForeground()
  let title = try renderTitle()
  return try await merge(background, foreground, title)
}

Actors:

actor Statistics {
  private var counter: Int = 0
  func increment() {
    counter += 1
  }
  func publish() async {
    await sendResults(counter)
  }
}

var statistics = Statistics()
await statistics.increment()