0
0
Swiftprogramming~20 mins

Throwing functions with throws in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Throws Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a throwing function call
What is the output of this Swift code when calling checkNumber(5)?
Swift
enum NumberError: Error {
    case tooSmall
}

func checkNumber(_ num: Int) throws -> String {
    if num < 10 {
        throw NumberError.tooSmall
    }
    return "Number is \(num)"
}

var result: String

do {
    result = try checkNumber(5)
} catch {
    result = "Error caught"
}
print(result)
AError caught
BNumber is 5
CCompilation error
DRuntime crash
Attempts:
2 left
💡 Hint
Remember that the function throws an error if the number is less than 10.
Predict Output
intermediate
2:00remaining
Value of variable after try? usage
What is the value of output after running this Swift code?
Swift
enum MyError: Error {
    case fail
}

func riskyFunction(_ flag: Bool) throws -> String {
    if flag {
        return "Success"
    } else {
        throw MyError.fail
    }
}

let output = try? riskyFunction(false)
print(output ?? "nil")
Anil
BSuccess
CCompilation error
DRuntime crash
Attempts:
2 left
💡 Hint
The try? converts errors to nil.
🔧 Debug
advanced
2:00remaining
Identify the error in throwing function usage
What error does this Swift code produce when compiled?
Swift
enum SampleError: Error {
    case errorCase
}

func test() throws {
    throw SampleError.errorCase
}

func callTest() {
    try test()
    print("Done")
}
ANo error, prints "Done"
BError: Call can throw but is not marked with try
CError: Missing catch block for try
DError: Function callTest must be marked with throws
Attempts:
2 left
💡 Hint
Check the function call inside callTest and its error handling.
📝 Syntax
advanced
2:00remaining
Correct syntax for throwing function declaration
Which option shows the correct way to declare a throwing function in Swift?
A
func fetchData() throw -&gt; String {
    return "Data"
}
B
func fetchData() -&gt; throws String {
    return "Data"
}
C
func fetchData() throws -&gt; String {
    return "Data"
}
D
func fetchData() throws String {
    return "Data"
}
Attempts:
2 left
💡 Hint
The keyword 'throws' comes after the parentheses and before the return arrow.
🚀 Application
expert
3:00remaining
Number of items in dictionary after throwing function filter
Given this Swift code, how many items are in the resulting dictionary filteredDict?
Swift
enum FilterError: Error {
    case invalidValue
}

func filterDict(_ dict: [Int: Int]) throws -> [Int: Int] {
    var result = [Int: Int]()
    for (key, value) in dict {
        if value < 0 {
            throw FilterError.invalidValue
        }
        if value % 2 == 0 {
            result[key] = value
        }
    }
    return result
}

let inputDict = [1: 2, 2: -1, 3: 4, 4: 5]

var filteredDict = [Int: Int]()
do {
    filteredDict = try filterDict(inputDict)
} catch {
    filteredDict = [:]
}
print(filteredDict.count)
A2
B0
C1
D3
Attempts:
2 left
💡 Hint
The function throws an error if any value is negative, causing the catch block to run.