0
0
Swiftprogramming~10 mins

Dictionary methods and default values 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 get the value for key "apple" from the dictionary.

Swift
let fruits = ["apple": 3, "banana": 5]
let count = fruits[[1]]
Drag options to blanks, or click blank then click option'
A"orange"
B"apple"
C"banana"
D"grape"
Attempts:
3 left
💡 Hint
Common Mistakes
Using a key that does not exist in the dictionary.
Forgetting to put the key inside quotes.
2fill in blank
medium

Complete the code to provide a default value of 0 when the key is missing.

Swift
let fruits = ["apple": 3, "banana": 5]
let count = fruits["orange", default: [1]]
Drag options to blanks, or click blank then click option'
Anil
B5
C-1
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using nil as a default value which is not allowed here.
Using a default value that does not match the dictionary's value type.
3fill in blank
hard

Fix the error in updating the dictionary value safely.

Swift
var fruits = ["apple": 3, "banana": 5]
fruits["apple"] = fruits["apple"]! [1] 2
Drag options to blanks, or click blank then click option'
A+
B-
C*
D/
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction or multiplication instead of addition.
Forgetting to unwrap the optional value before adding.
4fill in blank
hard

Fill both blanks to create a dictionary with squares of numbers greater than 3.

Swift
let squares = [[1]: [2] for num in 1...5 if num > 3]
Drag options to blanks, or click blank then click option'
Anum
Bnum * num
Cnum + num
Dnum - 1
Attempts:
3 left
💡 Hint
Common Mistakes
Using addition or subtraction instead of multiplication for squares.
Using the wrong variable as key or value.
5fill in blank
hard

Fill all three blanks to filter dictionary items with values greater than 4 and map keys to uppercase.

Swift
let fruits = ["apple": 3, "banana": 5, "cherry": 7]
let filtered = [[1]: [2] for (key, value) in fruits where value [3] 4]
Drag options to blanks, or click blank then click option'
Akey.uppercased()
Bvalue
C>
Dkey
Attempts:
3 left
💡 Hint
Common Mistakes
Not converting keys to uppercase.
Using wrong comparison operator or value.