Skip to content

Instantly share code, notes, and snippets.

@JarvisTheAvenger
Last active August 7, 2021 05:01
Show Gist options
  • Save JarvisTheAvenger/35fa5831d85d6da255e4751156bf1f5a to your computer and use it in GitHub Desktop.
Save JarvisTheAvenger/35fa5831d85d6da255e4751156bf1f5a to your computer and use it in GitHub Desktop.
Async-Await
import Foundation
// Async - Await - requires Xcode 13 and later
// yielding the thread
/*
Swift suspends the execution of your code on the current thread and runs some other code on that thread instead.
Because code with await needs to be able to suspend execution, only certain places in your program can call asynchronous functions or methods:
1. Code in the body of an asynchronous function, method, or property.
2. Code in the static main() method of a structure, class, or enumeration that’s marked with @main.
*/
func listPhotos(inGallery name: String) async -> [String] {
let result = [""] // some async code
return result
}
func downloadPhoto(named: String) async -> String {
let result = "" // some async code
return result
}
func show(_ photo: String) {
// Show photo
}
let photoNames = await listPhotos(inGallery: "Summer Vacation")
let sortedNames = photoNames.sorted()
let name = sortedNames[0]
let photo = await downloadPhoto(named: name)
show(photo)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment