0
0
Swiftprogramming~10 mins

Why error handling is explicit in Swift - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a function that can throw an error.

Swift
func readFile() [1] { }
Drag options to blanks, or click blank then click option'
Athrows
Bthrow
Ctry
Dcatch
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'throw' instead of 'throws' to declare the function.
Confusing 'try' with the function declaration keyword.
2fill in blank
medium

Complete the code to call a throwing function with error handling.

Swift
do {
    try readFile()
} [1] {
    print("Error occurred")
}
Drag options to blanks, or click blank then click option'
Atry
Bthrow
Cthrows
Dcatch
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'throws' instead of 'catch' after the do block.
Placing 'try' outside the do block.
3fill in blank
hard

Fix the error in the code to correctly handle errors when calling a throwing function.

Swift
let result = [1] readFile()
Drag options to blanks, or click blank then click option'
AreadFile()
Bthrows
Ctry
Dcatch
Attempts:
3 left
💡 Hint
Common Mistakes
Calling the function without 'try' causes a compile error.
Using 'throws' instead of 'try' when calling the function.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that filters keys with values greater than 10.

Swift
let filtered = dictionary.filter { $0.value [1] 10 }.map { ($0.key, $0.value) }.reduce(into: [:]) { $0[$1.[2]] = $1.1 }
Drag options to blanks, or click blank then click option'
A>
B<
Ckey
Dvalue
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' in the filter condition.
Using 'value' instead of 'key' when accessing dictionary keys.
5fill in blank
hard

Fill all three blanks to create a throwing function that reads a file and returns its content length if successful.

Swift
func readFile() [1] -> Int {{
    let content = try String(contentsOfFile: "file.txt")
    return content.[2]
}}

let length = try? readFile() [3] nil
Drag options to blanks, or click blank then click option'
Athrows
Bcount
C??
Dtry
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting 'throws' in the function declaration.
Using 'length' instead of 'count' for string length.
Not using '??' to handle the optional result.