0
0
Swiftprogramming~10 mins

Try? for optional result in Swift - Interactive Code Practice

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

Complete the code to convert the string to an integer.

Swift
let number = Int("123")
print([1])
Drag options to blanks, or click blank then click option'
Anumber
BInt
Ctry
D123
Attempts:
3 left
💡 Hint
Common Mistakes
Using Int instead of the variable name.
Trying to print try keyword.
Printing the string literal instead of the variable.
2fill in blank
medium

Complete the code to safely unwrap the optional integer using if let.

Swift
if let value = [1] {
    print("Value is \(value)")
} else {
    print("Conversion failed")
}
Drag options to blanks, or click blank then click option'
AInt("456")
BInt("abc")
Ctry Int("456")
Dnumber
Attempts:
3 left
💡 Hint
Common Mistakes
Using try Int("456") causes a compile error.
Using Int("abc") which returns nil.
Using an undefined variable number.
3fill in blank
hard

Fix the error in the code by completing the try? expression.

Swift
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")
Drag options to blanks, or click blank then click option'
Atry!
Btry??
Ctry?
Dtry
Attempts:
3 left
💡 Hint
Common Mistakes
Using try without handling errors causes a compile error.
Using try! which crashes if an error is thrown.
Using invalid syntax like try??.
4fill in blank
hard

Fill both blanks to create a dictionary of word lengths only for words longer than 3 characters.

Swift
let words = ["apple", "cat", "banana", "dog"]
let lengths = [word: [1] for word in words if word.[2] 3]
Drag options to blanks, or click blank then click option'
Aword.count
Bcount
Ccount >
Dcount <
Attempts:
3 left
💡 Hint
Common Mistakes
Using just count without word. prefix.
Using count < 3 which filters shorter words.
Using word.count but wrong comparison operator.
5fill in blank
hard

Fill all three blanks to create a dictionary with uppercase keys and values only for positive numbers.

Swift
let data = ["a": 1, "b": -2, "c": 3]
let filtered = [[1]: [2] for (key, value) in data where value [3] 0]
Drag options to blanks, or click blank then click option'
Akey.uppercased()
Bvalue
C>
Dkey
Attempts:
3 left
💡 Hint
Common Mistakes
Using key instead of key.uppercased().
Using value < 0 which filters negative numbers.
Swapping keys and values in the dictionary comprehension.