println dictionary has “Optional”

后端 未结 2 529
离开以前
离开以前 2020-12-02 02:47

Consider this snippet:

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


        
相关标签:
2条回答
  • 2020-12-02 03:09

    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

    0 讨论(0)
  • 2020-12-02 03:28

    In Swift, dictionaries return optionals because if you try to access a key that does not exist, it can return nil

    0 讨论(0)
提交回复
热议问题