0
0
Swiftprogramming~20 mins

Async functions declaration in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Async Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of an async function call with await
What is the output of this Swift code when run in an async context?
Swift
func fetchNumber() async -> Int {
    return 42
}

Task {
    let result = await fetchNumber()
    print(result)
}
ACompilation error: missing await
B42
CRuntime error: cannot call async function
D0
Attempts:
2 left
💡 Hint
Remember to use 'await' when calling async functions inside async contexts.
Predict Output
intermediate
2:00remaining
Return type of async function
What is the type of the variable 'value' after this code runs?
Swift
func getString() async -> String {
    return "Hello"
}

Task {
    let value = await getString()
    print(type(of: value))
}
AVoid
BOptional<String>
CTask<String, Never>
DString
Attempts:
2 left
💡 Hint
The 'await' keyword unwraps the async result to its return type.
Predict Output
advanced
2:00remaining
Async function with throwing error
What will be printed when this code runs?
Swift
enum MyError: Error {
    case failed
}

func riskyTask() async throws -> String {
    throw MyError.failed
}

Task {
    do {
        let result = try await riskyTask()
        print(result)
    } catch {
        print("Error caught")
    }
}
ARuntime crash
BCompilation error: missing try
CError caught
DNo output
Attempts:
2 left
💡 Hint
Async functions that throw must be called with 'try await' inside a do-catch block.
🧠 Conceptual
advanced
2:00remaining
Correct async function declaration
Which of the following is the correct way to declare an async function in Swift that returns an integer?
Afunc compute() async -> Int { return 10 }
Basync func compute() -> Int { return 10 }
Cfunc async compute() -> Int { return 10 }
Dfunc compute() -> async Int { return 10 }
Attempts:
2 left
💡 Hint
The 'async' keyword goes after the function parentheses.
Predict Output
expert
3:00remaining
Async function call order and output
What is the output of this Swift code?
Swift
func first() async -> String {
    return "First"
}

func second() async -> String {
    return "Second"
}

Task {
    async let a = first()
    async let b = second()
    let result = await a + " & " + await b
    print(result)
}
AFirst & Second
BSecond & First
CCompilation error: cannot concatenate async let results
DRuntime error: deadlock
Attempts:
2 left
💡 Hint
async let allows concurrent execution; awaiting each unwraps the result.