Add async/await/actor test samples

This commit is contained in:
Nick Lockwood
2021-05-29 09:53:46 +01:00
parent a148209d15
commit f482d1afe5
8 changed files with 120 additions and 0 deletions
+25
View File
@@ -0,0 +1,25 @@
actor SafeCollector {
var deck: Set<String>
init(deck: Set<String>) {
self.deck = deck
}
func send(card selected: String, to person: SafeCollector) async -> Bool {
guard deck.contains(selected) else { return false }
deck.remove(selected)
await person.transfer(card: selected)
return true
}
func transfer(card: String) {
deck.insert(card)
}
}
class NewDataController {
@MainActor func save() {
print("Saving data…")
}
}
+41
View File
@@ -0,0 +1,41 @@
func processWeather() async {
let records = await fetchWeatherHistory()
let average = await calculateAverageTemperature(for: records)
let response = await upload(result: average)
print("Server response: \(response)")
}
enum UserError: Error {
case invalidCount, dataTooLong
}
func fetchUsers(count: Int) async throws -> [String] {
if count > 3 {
// Don't attempt to fetch too many users
throw UserError.invalidCount
}
// Complex networking code here; we'll just send back up to `count` users
return Array(["Antoni", "Karamo", "Tan"].prefix(count))
}
func save(users: [String]) async throws -> String {
let savedUsers = users.joined(separator: ",")
if savedUsers.count > 32 {
throw UserError.dataTooLong
} else {
// Actual saving code would go here
return "Saved \(savedUsers)!"
}
}
func updateUsers() async {
do {
let users = try await fetchUsers(count: 3)
let result = try await save(users: users)
print(result)
} catch {
print("Oops!")
}
}
+23
View File
@@ -0,0 +1,23 @@
func printUserDetails() async {
async let username = getUser()
async let scores = getHighScores()
async let friends = getFriends()
let user = await UserData(name: username, friends: friends, highScores: scores)
print("Hello, my name is \(user.name), and I have \(user.friends.count) friends!")
}
enum NumberError: Error {
case outOfRange
}
func fibonacci(of number: Int) async throws -> Int {
if number < 0 || number > 22 {
throw NumberError.outOfRange
}
if number < 2 { return number }
async let first = fibonacci(of: number - 2)
async let second = fibonacci(of: number - 1)
return try await first + second
}
+11
View File
@@ -0,0 +1,11 @@
func printAllDoubles() async {
for await number in DoubleGenerator() {
print(number)
}
}
func containsExactNumber() async {
let doubles = DoubleGenerator()
let match = await doubles.contains(16_777_216)
print(match)
}
+13
View File
@@ -0,0 +1,13 @@
var contents: String {
get async throws {
guard let url = Bundle.main.url(forResource: filename, withExtension: nil) else {
throw FileError.missing
}
do {
return try String(contentsOf: url)
} catch {
throw FileError.unreadable
}
}
}
+3
View File
@@ -0,0 +1,3 @@
func setScore2(@Clamped(range: 0 ... 100) to score: Int) {
print("Setting score to \(score)")
}
+1
View File
@@ -0,0 +1 @@
Async/await test samples from https://www.hackingwithswift.com/articles/233/whats-new-in-swift-5-5
+3
View File
@@ -0,0 +1,3 @@
func runLater(_ function: @escaping @Sendable () -> Void) {
DispatchQueue.global().asyncAfter(deadline: .now() + 3, execute: function)
}