Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
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.
✗ Incorrect
Use 'await' to wait for the async function 'fetchData()' to complete and get its result.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'async' instead of 'await' before the function call.
Calling the async function without 'await' causing errors.
✗ Incorrect
Inside an async function, use 'await' to wait for another async function's result.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting 'await' causing compile errors.
Using 'async' incorrectly before the function call.
✗ Incorrect
You must use 'await' before calling an async function to wait for its result.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Marking only one function as async causing errors.
Using 'await' in the function signature instead of 'async'.
✗ Incorrect
The function 'getGreeting' must be marked 'async' to be asynchronous, and 'greet' must also be 'async' to call it with 'await'.
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting 'await' before the async call.
Using wrong comparison operator or variable name.
✗ Incorrect
Use 'await' to wait for 'fetchValue', compare 'value' with '>' 3, and use 'key' as dictionary key.