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

后端 未结 2 823
[愿得一人]
[愿得一人] 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:12

    Use subscripting to access the value for a dictionary key. This will return an Optional:

    let apple: String? = companies["AAPL"]
    

    or

    if let apple = companies["AAPL"] {
        // ...
    }
    

    You can also enumerate over all of the keys and values:

    var companies = ["AAPL" : "Apple Inc", "GOOG" : "Google Inc", "AMZN" : "Amazon.com, Inc", "FB" : "Facebook Inc"]
    
    for (key, value) in companies {
        print("\(key) -> \(value)")
    }
    

    Or enumerate over all of the values:

    for value in Array(companies.values) {
        print("\(value)")
    }
    

提交回复
热议问题