The println dictionary has an option "Optional"

Consider this snippet:

let interestingNumbers = [
    "Prime": [2, 3, 5, 7, 11, 13],
    "Fibonacci": [1, 1, 2, 3, 5, 8],
    "Square": [1, 4, 9, 16, 25],
]
println(interestingNumbers["Square"])

let individualScores = [75, 43, 103, 87, 12]
println(individualScores)

      

Console output:

Optional ([1, 4, 9, 16, 25])

[75, 43, 103, 87, 12]

Why was "Optional" in the dictionary?

+2


source to share


2 answers


Swift dictionaries return security options. If you try to access a key that doesn't exist, this will give you null.

You can also use the index syntax to get a value from a dictionary for a specific key. Because it is possible to query for a key for which there is no value, the dictionaries index index returns an optional value of the dictionaries value type. If the dictionary contains a value for the requested key, the index returns an optional value that contains the existing value for that key. Otherwise the index returns nil

From Swift Programming language



and

Use subscriptions to access individual items in any dictionary. Is the value returned from the dictionary index of type ValueType? - optional with the base dictionary type ValueType

From Swift Standard Reference

+4


source


In Swift, dictionaries return parameters because if you try to access a key that doesn't exist it might return nil



+1


source







All Articles