Complete the code to force unwrap the result of the throwing function using try!
func getNumber() throws -> Int {
return 42
}
let number = [1] getNumber()try without handling errors causes a compile error.try? returns an optional, not a forced unwrap.catch is for error handling, not unwrapping.Using try! forces the program to unwrap the result of a throwing function. If the function throws an error, the program will crash.
Complete the code to force unwrap the string returned by the throwing function using try!
func fetchName() throws -> String {
return "Alice"
}
let name: String = [1] fetchName()try? returns an optional String, not a forced unwrap.try without a do-catch block causes an error.catch is not valid syntax here.try! unwraps the result directly and crashes if an error is thrown.
Fix the error by force unwrapping the result of the throwing function using try!
func getValue() throws -> Double {
return 3.14
}
let value = [1] getValue()try without a do-catch block causes a compile error.try? returns an optional, not a forced unwrap.catch is not valid here.Using try! forces the unwrap of the throwing function's result, fixing the error.
Fill both blanks to populate the dictionary that stores the forced unwrapped length of each word if the length is greater than 3.
func getLength(_ word: String) throws -> Int {
return word.count
}
let words = ["apple", "cat", "banana", "dog"]
var lengths = [String: Int]()
for word in words {
if [1](word).count [2] 3 {
lengths[word] = try! getLength(word)
}
}Int(word) instead of String(word) causes errors.< instead of > changes the logic.try! to force unwrap the function result.We use String(word).count to get the length of the word and check if it is greater than 3.
Fill both blanks to create a dictionary that maps uppercase words to their forced unwrapped lengths if the length is greater than 4.
func getLength(_ word: String) throws -> Int {
return word.count
}
let words = ["apple", "pear", "banana", "kiwi"]
var lengths = [String: Int]()
for word in words {
if word.count [1] 4 {
lengths[word[2]] = try! getLength(word)
}
}< instead of > changes the condition..lowercased() instead of .uppercased() changes the key.try! to force unwrap the function result.The code checks if the word length is greater than 4, then uses .uppercased() to make the key uppercase and stores the forced unwrapped length.