Complete the code to convert the string to an integer.
let number = Int("123") print([1])
Int instead of the variable name.try keyword.The variable number holds the optional integer result from Int("123"). Printing number shows the optional value.
Complete the code to safely unwrap the optional integer using if let.
if let value = [1] { print("Value is \(value)") } else { print("Conversion failed") }
try Int("456") causes a compile error.Int("abc") which returns nil.number.Using Int("456") returns an optional integer. The if let safely unwraps it to value.
Fix the error in the code by completing the try? expression.
func parseNumber(_ text: String) throws -> Int {
if let number = Int(text) {
return number
} else {
throw NSError(domain: "ParseError", code: 1)
}
}
let result = [1] parseNumber("789")
print(result.map(String.init) ?? "No number")try without handling errors causes a compile error.try! which crashes if an error is thrown.try??.The try? keyword converts the throwing function result into an optional, returning nil if an error occurs.
Fill both blanks to create a dictionary of word lengths only for words longer than 3 characters.
let words = ["apple", "cat", "banana", "dog"] let lengths = [word: [1] for word in words if word.[2] 3]
count without word. prefix.count < 3 which filters shorter words.word.count but wrong comparison operator.word.count gets the length of each word. The condition count > 3 filters words longer than 3 characters.
Fill all three blanks to create a dictionary with uppercase keys and values only for positive numbers.
let data = ["a": 1, "b": -2, "c": 3] let filtered = [[1]: [2] for (key, value) in data where value [3] 0]
key instead of key.uppercased().value < 0 which filters negative numbers.key.uppercased() converts keys to uppercase. The dictionary includes only entries where value > 0.