Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
792 views
in Technique[技术] by (71.8m points)

swift - println dictionary has "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)

The console output:

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

[75, 43, 103, 87, 12]

Why was there an "Optional" in the dictionary case?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Swift dictionaries are returning optionals for safety. If you try to access a key which does not exists that would give you nil.

You can also use subscript syntax to retrieve a value from the dictionary for a particular key. Because it is possible to request a key for which no value exists, a dictionary’s subscript returns an optional value of the dictionary’s value type. If the dictionary contains a value for the requested key, the subscript returns an optional value containing the existing value for that key. Otherwise, the subscript returns nil

From The Swift Programming Language

and

Use subscripting to access the individual elements in any dictionary. The value returned from a dictionary's subscript is of type ValueType? — an optional with an underlying type of the dictionary’s ValueType

From the Swift Standard Library Reference


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...