0
0
Swiftprogramming~10 mins

Await for calling async functions 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 call the async function and wait for its result.

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

func load() async {
    let result = [1] fetchData()
    print(result)
}
Drag options to blanks, or click blank then click option'
Aawait
Basync
Cdefer
Dtry
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'async' instead of 'await' before the function call.
Forgetting to use any keyword and calling the function directly.
2fill in blank
medium

Complete the code to define an async function that waits for another async function.

Swift
func getNumber() async -> Int {
    return 42
}

func printNumber() async {
    let number = [1] getNumber()
    print("Number is \(number)")
}
Drag options to blanks, or click blank then click option'
Atry
Basync
Cdefer
Dawait
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'async' instead of 'await' before the function call.
Calling the async function without 'await' causing errors.
3fill in blank
hard

Fix the error in calling the async function by adding the missing keyword.

Swift
func fetchMessage() async -> String {
    return "Hello!"
}

func showMessage() async {
    let message = [1] fetchMessage()
    print(message)
}
Drag options to blanks, or click blank then click option'
Aawait
Basync
Cdefer
Dtry
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting 'await' causing compile errors.
Using 'async' incorrectly before the function call.
4fill in blank
hard

Fill both blanks to create an async function that calls another async function and prints its result.

Swift
func getGreeting() [1] -> String {
    return "Hi there!"
}

func greet() [2] {
    let greeting = await getGreeting()
    print(greeting)
}
Drag options to blanks, or click blank then click option'
Aasync
Bawait
Cthrows
Ddefer
Attempts:
3 left
💡 Hint
Common Mistakes
Marking only one function as async causing errors.
Using 'await' in the function signature instead of 'async'.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that awaits async calls and filters results.

Swift
func fetchValue(_ key: String) async -> Int {
    return key.count
}

func buildDict(keys: [String]) async -> [String: Int] {
    var dict = [String: Int]()
    for key in keys {
        let value = [1] fetchValue(key)
        if value [2] 3 {
            dict[[3]] = value
        }
    }
    return dict
}
Drag options to blanks, or click blank then click option'
Aawait
B>
Ckey
Dasync
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting 'await' before the async call.
Using wrong comparison operator or variable name.