Bird
Raised Fist0
Swiftprogramming~20 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What does the throws keyword indicate when used in a Swift function declaration?
easy
A. The function cannot be called outside its module.
B. The function always returns a Boolean value.
C. The function can produce an error that must be handled.
D. The function runs asynchronously.

Solution

  1. Step 1: Understand the role of throws

    The throws keyword marks a function that can produce an error during execution.
  2. Step 2: Recognize error handling requirement

    Calling a throws function requires handling the possible error with try and do-catch.
  3. Final Answer:

    The function can produce an error that must be handled. -> Option C
  4. Quick Check:

    throws means function can throw error [OK]
Hint: Throws means function can fail and needs error handling [OK]
Common Mistakes:
  • Thinking throws means async function
  • Assuming throws means function returns Bool
  • Confusing throws with access control keywords
2. Which of the following is the correct way to declare a throwing function in Swift?
easy
A. func fetchData() -> throws String
B. func fetchData() throw -> String
C. func fetchData() throws String
D. func fetchData() throws -> String

Solution

  1. Step 1: Recall correct syntax for throwing functions

    In Swift, throws comes after the parentheses and before the return type.
  2. Step 2: Match syntax with options

    func fetchData() throws -> String matches the correct syntax: func name() throws -> ReturnType.
  3. Final Answer:

    func fetchData() throws -> String -> Option D
  4. Quick Check:

    Correct syntax is throws after () [OK]
Hint: Put throws right after () before return type [OK]
Common Mistakes:
  • Writing throw instead of throws
  • Placing throws after return type
  • Omitting throws keyword
3. What will be the output of the following Swift code?
enum FileError: Error {
    case notFound
}

func readFile() throws -> String {
    throw FileError.notFound
}

do {
    let content = try readFile()
    print(content)
} catch {
    print("Error occurred")
}
medium
A. Compilation error
B. Error occurred
C. No output
D. notFound

Solution

  1. Step 1: Analyze the throwing function behavior

    The function readFile() always throws FileError.notFound error.
  2. Step 2: Understand the do-catch block

    The try calls readFile(), which throws, so control moves to catch block printing "Error occurred".
  3. Final Answer:

    Error occurred -> Option B
  4. Quick Check:

    Thrown error triggers catch printing message [OK]
Hint: Thrown error triggers catch block output [OK]
Common Mistakes:
  • Expecting thrown error value to print
  • Ignoring that error causes catch block
  • Thinking no output occurs
4. Identify the error in this Swift code snippet:
func riskyOperation() throws -> Int {
    return 42
}

let result = riskyOperation()
print(result)
medium
A. Missing try keyword when calling riskyOperation()
B. Function should not return Int
C. Throws keyword is not allowed here
D. Missing catch block after function call

Solution

  1. Step 1: Check calling syntax for throwing functions

    Calling a function marked with throws requires using try keyword.
  2. Step 2: Identify missing try keyword

    The code calls riskyOperation() without try, causing a compile error.
  3. Final Answer:

    Missing try keyword when calling riskyOperation() -> Option A
  4. Quick Check:

    Throwing functions need try when called [OK]
Hint: Use try when calling throws functions [OK]
Common Mistakes:
  • Calling throws function without try
  • Assuming throws means no return value
  • Forgetting to handle errors with do-catch
5. You want to write a function parseNumber(from: String) that throws an error if the string is not a valid integer. Which of the following implementations correctly uses throws and error handling?
hard
A. enum ParseError: Error { case invalidFormat } func parseNumber(from text: String) throws -> Int { guard let number = Int(text) else { throw ParseError.invalidFormat } return number }
B. func parseNumber(from text: String) -> Int { if Int(text) == nil { print("Invalid format") } return Int(text) ?? 0 }
C. enum ParseError: Error { case invalidFormat } func parseNumber(from text: String) -> Int throws { if Int(text) == nil { throw ParseError.invalidFormat } return Int(text)! }
D. func parseNumber(from text: String) throws -> Int { if Int(text) == nil { return 0 } return Int(text)! }

Solution

  1. Step 1: Check function signature and error throwing

    enum ParseError: Error { case invalidFormat } func parseNumber(from text: String) throws -> Int { guard let number = Int(text) else { throw ParseError.invalidFormat } return number } correctly declares throws after parameters and before return type, and throws error if parsing fails.
  2. Step 2: Verify error throwing logic

    enum ParseError: Error { case invalidFormat } func parseNumber(from text: String) throws -> Int { guard let number = Int(text) else { throw ParseError.invalidFormat } return number } uses guard let to safely unwrap Int, throwing ParseError.invalidFormat if conversion fails.
  3. Final Answer:

    Correctly implements throwing function with error handling. -> Option A
  4. Quick Check:

    Throws declared and error thrown on invalid input [OK]
Hint: Use guard and throw error inside throws function [OK]
Common Mistakes:
  • Not marking function with throws
  • Throwing error outside throws function
  • Returning default instead of throwing error
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard