如何在Swift中从字典中获取key的值?

wwwo4jvm  于 2023-06-21  发布在  Swift
关注(0)|答案(4)|浏览(207)

我有一本Swift字典。我想得到密钥的值。关键字方法的对象对我不起作用。如何获取字典键的值?
这是我的字典:

var companies = ["AAPL" : "Apple Inc", "GOOG" : "Google Inc", "AMZN" : "Amazon.com, Inc", "FB" : "Facebook Inc"]

for name in companies.keys { 
    print(companies.objectForKey("AAPL"))
}
sxissh06

sxissh061#

使用下标访问字典键的值。这将返回一个可选的:

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

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

你也可以枚举所有的键和值:

var companies = ["AAPL" : "Apple Inc", "GOOG" : "Google Inc", "AMZN" : "Amazon.com, Inc", "FB" : "Facebook Inc"]

for (key, value) in companies {
    print("\(key) -> \(value)")
}

或者枚举所有值:

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

pn9klfpd2#

关于Apple Docs
可以使用下标语法从字典中检索特定键的值。因为可以请求不存在值的键,所以字典的下标返回字典的值类型的可选值。如果字典包含所请求键的值,则下标返回一个可选值,其中包含该键的现有值。否则,下标返回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."
llycmphe

llycmphe3#

要查找值,请使用以下内容

if let a = companies["AAPL"] {
   // a is the value
}

用于遍历字典

for (key, value) in companies {
    print(key,"---", value)
}

最后,对于按值搜索键,首先添加扩展名

extension Dictionary where Value: Equatable {
    func findKey(forValue val: Value) -> Key? {
        return first(where: { $1 == val })?.key
    }
}

那就打电话吧

companies.findKey(val : "Apple Inc")
htrmnn0y

htrmnn0y4#

var dic=["Saad":5000,"Manoj":2000,"Aditya":5000,"chintan":1000]

print("salary of Saad id \(dic["Saad"]!)")

访问字典的成员,你必须包括!(惊叹)
!=>它的意思是强制展开文档强制展开details

相关问题