How can I get key's value from dictionary in Swift?

后端 未结 2 824
[愿得一人]
[愿得一人] 2020-12-13 05:11

I have a Swift dictionary. I want to get my key\'s value. Object for key method is not working for me. How do you get the value for a dictionary\'s key?

This is my d

2条回答
  •  青春惊慌失措
    2020-12-13 06:17

    From Apple Docs

    You can 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:

    https://developer.apple.com/documentation/swift/dictionary

    if let airportName = airports["DUB"] {
        print("The name of the airport is \(airportName).")
    } else {
        print("That airport is not in the airports dictionary.")
    }
    // prints "The name of the airport is Dublin Airport."
    

提交回复
热议问题