View in English

  • Apple Developer
    • Get Started

    Explore Get Started

    • Overview
    • Learn
    • Apple Developer Program

    Stay Updated

    • Latest News
    • Hello Developer
    • Platforms

    Explore Platforms

    • Apple Platforms
    • iOS
    • iPadOS
    • macOS
    • tvOS
    • visionOS
    • watchOS
    • App Store

    Featured

    • Design
    • Distribution
    • Games
    • Accessories
    • Web
    • Home
    • CarPlay
    • Technologies

    Explore Technologies

    • Overview
    • Xcode
    • Swift
    • SwiftUI

    Featured

    • Accessibility
    • App Intents
    • Apple Intelligence
    • Games
    • Machine Learning & AI
    • Security
    • Xcode Cloud
    • Community

    Explore Community

    • Overview
    • Meet with Apple events
    • Community-driven events
    • Developer Forums
    • Open Source

    Featured

    • WWDC
    • Swift Student Challenge
    • Developer Stories
    • App Store Awards
    • Apple Design Awards
    • Apple Developer Centers
    • Documentation

    Explore Documentation

    • Documentation Library
    • Technology Overviews
    • Sample Code
    • Human Interface Guidelines
    • Videos

    Release Notes

    • Featured Updates
    • iOS
    • iPadOS
    • macOS
    • watchOS
    • visionOS
    • tvOS
    • Xcode
    • Downloads

    Explore Downloads

    • All Downloads
    • Operating Systems
    • Applications
    • Design Resources

    Featured

    • Xcode
    • TestFlight
    • Fonts
    • SF Symbols
    • Icon Composer
    • Support

    Explore Support

    • Overview
    • Help Guides
    • Developer Forums
    • Feedback Assistant
    • Contact Us

    Featured

    • Account Help
    • App Review Guidelines
    • App Store Connect Help
    • Upcoming Requirements
    • Agreements and Guidelines
    • System Status
  • Quick Links

    • Events
    • News
    • Forums
    • Sample Code
    • Videos
 

Vidéos

Ouvrir le menu Fermer le menu
  • Collections
  • Toutes les vidéos
  • À propos

Plus de vidéos

  • À propos
  • Code
  • Explore structured concurrency in Swift

    When you have code that needs to run at the same time as other code, it's important to choose the right tool for the job. We'll take you through the different kinds of concurrent tasks you can create in Swift, show you how to create groups of tasks, and find out how to cancel tasks in progress. We'll also provide guidance on when you may want to use unstructured tasks.

    To get the most out of this session, we first recommend watching “Meet async/await in Swift.”

    Ressources

    • SE-0317: async let
    • SE-0304: Structured concurrency
    • The Swift Programming Language: Concurrency
      • Vidéo HD
      • Vidéo SD

    Vidéos connexes

    WWDC23

    • Beyond the basics of structured concurrency

    WWDC22

    • Eliminate data races using Swift Concurrency
    • Visualize and optimize Swift concurrency

    WWDC21

    • Discover concurrency in SwiftUI
    • Meet async/await in Swift
    • Meet AsyncSequence
    • Protect mutable state with Swift actors
    • Swift concurrency: Behind the scenes
    • Swift concurrency: Update a sample app
    • What‘s new in Swift
  • Rechercher dans cette vidéo…
    • 1:57 - Asynchronous code with completion handlers is unstructured

      func fetchThumbnails(
          for ids: [String],
          completion handler: @escaping ([String: UIImage]?, Error?) -> Void
      ) {
          guard let id = ids.first else { return handler([:], nil) }
          let request = thumbnailURLRequest(for: id)
          let dataTask = URLSession.shared.dataTask(with: request) { data, response, error in
              guard let response = response,
                    let data = data
              else {
                  return handler(nil, error)
              }
              // ... check response ...
              UIImage(data: data)?.prepareThumbnail(of: thumbSize) { image in
                  guard let image = image else {
                      return handler(nil, ThumbnailFailedError())
                  }
                  fetchThumbnails(for: Array(ids.dropFirst())) { thumbnails, error in
                      // ... add image to thumbnails ...
                  }
              }
          }
          dataTask.resume()
      }
    • 2:56 - Asynchronous code with async/await is structured

      func fetchThumbnails(for ids: [String]) async throws -> [String: UIImage] {
          var thumbnails: [String: UIImage] = [:]
          for id in ids {
              let request = thumbnailURLRequest(for: id)
              let (data, response) = try await URLSession.shared.data(for: request)
              try validateResponse(response)
              guard let image = await UIImage(data: data)?.byPreparingThumbnail(ofSize: thumbSize) else {
                  throw ThumbnailFailedError()
              }
              thumbnails[id] = image
          }
          return thumbnails
      }
    • 7:59 - Structured concurrency with async-let

      func fetchOneThumbnail(withID id: String) async throws -> UIImage {
          let imageReq = imageRequest(for: id), metadataReq = metadataRequest(for: id)
          async let (data, _) = URLSession.shared.data(for: imageReq)
          async let (metadata, _) = URLSession.shared.data(for: metadataReq)
          guard let size = parseSize(from: try await metadata),
                let image = try await UIImage(data: data)?.byPreparingThumbnail(ofSize: size)
          else {
              throw ThumbnailFailedError()
          }
          return image
      }
    • 11:46 - Checking for cancellation by calling a method that throws

      func fetchThumbnails(for ids: [String]) async throws -> [String: UIImage] {
          var thumbnails: [String: UIImage] = [:]
          for id in ids {
              try Task.checkCancellation()
              thumbnails[id] = try await fetchOneThumbnail(withID: id)
          }
          return thumbnails
      }
    • 12:16 - Obtaining the cancellation status of the current task

      func fetchThumbnails(for ids: [String]) async throws -> [String: UIImage] {
          var thumbnails: [String: UIImage] = [:]
          for id in ids {
              if Task.isCancelled { break }
              thumbnails[id] = try await fetchOneThumbnail(withID: id)
          }
          return thumbnails
      }
    • 13:13 - Async-let is for concurrency with static width

      func fetchThumbnails(for ids: [String]) async throws -> [String: UIImage] {
          var thumbnails: [String: UIImage] = [:]
          for id in ids {
              thumbnails[id] = try await fetchOneThumbnail(withID: id)
          }
          return thumbnails
      }
      
      func fetchOneThumbnail(withID id: String) async throws -> UIImage {
          // ...
      
          async let (data, _) = URLSession.shared.data(for: imageReq)
          async let (metadata, _) = URLSession.shared.data(for: metadataReq)
      
          // ...
      }
    • 13:58 - A task group is for concurrency with dynamic width

      func fetchThumbnails(for ids: [String]) async throws -> [String: UIImage] {
          var thumbnails: [String: UIImage] = [:]
          try await withThrowingTaskGroup(of: Void.self) { group in
              for id in ids {
                  group.async {
                      // Error: Mutation of captured var 'thumbnails' in concurrently executing code
                      thumbnails[id] = try await fetchOneThumbnail(withID: id)
                  }
              }
          }
          return thumbnails
      }
    • 16:32 - Accessing the results of tasks within a group

      func fetchThumbnails(for ids: [String]) async throws -> [String: UIImage] {
          var thumbnails: [String: UIImage] = [:]
          try await withThrowingTaskGroup(of: (String, UIImage).self) { group in
              for id in ids {
                  group.async {
                      return (id, try await fetchOneThumbnail(withID: id))
                  }
              }
              // Obtain results from the child tasks, sequentially, in order of completion.
              for try await (id, thumbnail) in group {
                  thumbnails[id] = thumbnail
              }
          }
          return thumbnails
      }
    • 20:39 - Creating an unstructured task

      @MainActor
      class MyDelegate: UICollectionViewDelegate {
          func collectionView(_ view: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt item: IndexPath) {
              let ids = getThumbnailIDs(for: item)
              Task {
                  let thumbnails = await fetchThumbnails(for: ids)
                  display(thumbnails, in: cell)
              }
          }
      }
    • 22:11 - Cancelling unstructured tasks

      @MainActor
      class MyDelegate: UICollectionViewDelegate {
          var thumbnailTasks: [IndexPath: Task<Void, Never>] = [:]
          
          func collectionView(_ view: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt item: IndexPath) {
              let ids = getThumbnailIDs(for: item)
              thumbnailTasks[item] = Task {
                  defer { thumbnailTasks[item] = nil }
                  let thumbnails = await fetchThumbnails(for: ids)
                  display(thumbnails, in: cell)
              }
          }
          
          func collectionView(_ view: UICollectionView, didEndDisplay cell: UICollectionViewCell, forItemAt item: IndexPath) {
              thumbnailTasks[item]?.cancel()
          }
      }
    • 24:09 - Detaching a task

      @MainActor
      class MyDelegate: UICollectionViewDelegate {
          var thumbnailTasks: [IndexPath: Task<Void, Never>] = [:]
          
          func collectionView(_ view: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt item: IndexPath) {
              let ids = getThumbnailIDs(for: item)
              thumbnailTasks[item] = Task {
                  defer { thumbnailTasks[item] = nil }
                  let thumbnails = await fetchThumbnails(for: ids)
                  Task.detached(priority: .background) {
                      writeToLocalCache(thumbnails)
                  }
                  display(thumbnails, in: cell)
              }
          }
      }
    • 24:57 - Creating a task group inside a detached task

      @MainActor
      class MyDelegate: UICollectionViewDelegate {
          var thumbnailTasks: [IndexPath: Task<Void, Never>] = [:]
          
          func collectionView(_ view: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt item: IndexPath) {
              let ids = getThumbnailIDs(for: item)
              thumbnailTasks[item] = Task {
                  defer { thumbnailTasks[item] = nil }
                  let thumbnails = await fetchThumbnails(for: ids)
                  Task.detached(priority: .background) {
                      withTaskGroup(of: Void.self) { g in
                          g.async { writeToLocalCache(thumbnails) }
                          g.async { log(thumbnails) }
                          g.async { ... }
                      }
                  }
                  display(thumbnails, in: cell)
              }
          }
      }

Developer Footer

  • Vidéos
  • WWDC21
  • Explore structured concurrency in Swift
  • Open Menu Close Menu
    • iOS
    • iPadOS
    • macOS
    • tvOS
    • visionOS
    • watchOS
    • App Store
    Open Menu Close Menu
    • Swift
    • SwiftUI
    • Swift Playground
    • TestFlight
    • Xcode
    • Xcode Cloud
    • Icon Composer
    • SF Symbols
    Open Menu Close Menu
    • Accessibility
    • Accessories
    • Apple Intelligence
    • Audio & Video
    • Augmented Reality
    • Business
    • Design
    • Distribution
    • Education
    • Games
    • Health & Fitness
    • In-App Purchase
    • Localization
    • Maps & Location
    • Machine Learning & AI
    • Security
    • Safari & Web
    Open Menu Close Menu
    • Documentation
    • Downloads
    • Sample Code
    • Videos
    Open Menu Close Menu
    • Help Guides & Articles
    • Contact Us
    • Forums
    • Feedback & Bug Reporting
    • System Status
    Open Menu Close Menu
    • Apple Developer
    • App Store Connect
    • Certificates, IDs, & Profiles
    • Feedback Assistant
    Open Menu Close Menu
    • Apple Developer Program
    • Apple Developer Enterprise Program
    • App Store Small Business Program
    • MFi Program
    • Mini Apps Partner Program
    • News Partner Program
    • Video Partner Program
    • Security Bounty Program
    • Security Research Device Program
    Open Menu Close Menu
    • Meet with Apple
    • Apple Developer Centers
    • App Store Awards
    • Apple Design Awards
    • Apple Developer Academies
    • WWDC
    Read the latest news.
    Get the Apple Developer app.
    Copyright © 2026 Apple Inc. All rights reserved.
    Terms of Use Privacy Policy Agreements and Guidelines