0
0
Swiftprogramming~10 mins

Try! for forced unwrap 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 force unwrap the result of the throwing function using try!

Swift
func getNumber() throws -> Int {
    return 42
}

let number = [1] getNumber()
Drag options to blanks, or click blank then click option'
Atry?
Btry
Ctry!
Dcatch
Attempts:
3 left
💡 Hint
Common Mistakes
Using try without handling errors causes a compile error.
Using try? returns an optional, not a forced unwrap.
Using catch is for error handling, not unwrapping.
2fill in blank
medium

Complete the code to force unwrap the string returned by the throwing function using try!

Swift
func fetchName() throws -> String {
    return "Alice"
}

let name: String = [1] fetchName()
Drag options to blanks, or click blank then click option'
Acatch
Btry?
Ctry
Dtry!
Attempts:
3 left
💡 Hint
Common Mistakes
Using try? returns an optional String, not a forced unwrap.
Using try without a do-catch block causes an error.
Using catch is not valid syntax here.
3fill in blank
hard

Fix the error by force unwrapping the result of the throwing function using try!

Swift
func getValue() throws -> Double {
    return 3.14
}

let value = [1] getValue()
Drag options to blanks, or click blank then click option'
Atry
Btry!
Ctry?
Dcatch
Attempts:
3 left
💡 Hint
Common Mistakes
Using try without a do-catch block causes a compile error.
Using try? returns an optional, not a forced unwrap.
Using catch is not valid here.
4fill in blank
hard

Fill both blanks to populate the dictionary that stores the forced unwrapped length of each word if the length is greater than 3.

Swift
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)
    }
}
Drag options to blanks, or click blank then click option'
AString
B>
C<
DInt
Attempts:
3 left
💡 Hint
Common Mistakes
Using Int(word) instead of String(word) causes errors.
Using < instead of > changes the logic.
Not using try! to force unwrap the function result.
5fill in blank
hard

Fill both blanks to create a dictionary that maps uppercase words to their forced unwrapped lengths if the length is greater than 4.

Swift
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)
    }
}
Drag options to blanks, or click blank then click option'
A>
B.uppercased()
C<
D.lowercased()
Attempts:
3 left
💡 Hint
Common Mistakes
Using < instead of > changes the condition.
Using .lowercased() instead of .uppercased() changes the key.
Not using try! to force unwrap the function result.