0
0
Swiftprogramming~10 mins

Structured concurrency model in Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to start a new asynchronous task using Swift's structured concurrency.

Swift
Task.[1] {
    print("Hello from a new task!")
}
Drag options to blanks, or click blank then click option'
Adetached
Binit
Cstart
Drun
Attempts:
3 left
💡 Hint
Common Mistakes
Using Task.start or Task.run which do not exist.
Confusing Task.detached with Task.init.
2fill in blank
medium

Complete the code to await the result of an asynchronous function call.

Swift
func fetchData() async -> String {
    return "Data"
}

func process() async {
    let result = [1] fetchData()
    print(result)
}
Drag options to blanks, or click blank then click option'
Aawait
Bcall
Casync
Ddefer
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to use 'await' before calling an async function.
Using 'async' instead of 'await' in the function body.
3fill in blank
hard

Fix the error in the code by completing the blank to correctly create a child task within a task group.

Swift
func downloadAll() async {
    await withTaskGroup(of: String.self) { group in
        group.[1] {
            return "File 1"
        }
    }
}
Drag options to blanks, or click blank then click option'
AstartTask
BcreateTask
Claunch
DaddTask
Attempts:
3 left
💡 Hint
Common Mistakes
Using non-existent methods like startTask or createTask.
Trying to use Task.detached inside the group.
4fill in blank
hard

Fill both blanks to create a task group that collects results from multiple child tasks.

Swift
func fetchAll() async {
    let results = await withTaskGroup(of: String.self) { group in
        group.[1] {
            return "Data 1"
        }
        group.[2] {
            return "Data 2"
        }
    }
}
Drag options to blanks, or click blank then click option'
AaddTask
Bstart
Claunch
Dcreate
Attempts:
3 left
💡 Hint
Common Mistakes
Using different methods for each task.
Using methods that do not exist on the group.
5fill in blank
hard

Fill all three blanks to create a task group that adds tasks and processes their results.

Swift
func processFiles() async {
    await withTaskGroup(of: String.self) { group in
        group.[1] {
            return "File A"
        }
        group.[2] {
            return "File B"
        }
        for await result in group.[3] {
            print(result)
        }
    }
}
Drag options to blanks, or click blank then click option'
AaddTask
BstartTask
Cresults
Dtasks
Attempts:
3 left
💡 Hint
Common Mistakes
Using startTask instead of addTask.
Trying to iterate over group.tasks instead of group.results.