2017-05-09 91 views
1

我正在使用字典并试图在不知道或访问密钥的情况下获取该值。 这是我的字典看起来像"Olivia":[2.0, 0.0, 1.0, 3.0],"Amber":[60.0, 0.0, 0.0, 1.0]这是一个[String: ArrayDouble]字典,但我想检查是否有Value(ArrayDouble)中包含60.0的任何值,然后显示该值的密钥。我试图做的是:Swift字典获取值,但无法访问或不知道密钥

let number = 60.0 
for (key, value) in dict{ 

    if (number== value[0]){ 

    print(...the key) 

    }else{ 

} 

回答

1

你可以这样走。

let dic = ["Olivia":[2.0, 0.0, 1.0, 3.0],"Amber":[60.0, 0.0, 0.0, 1.0]] 
let filterKeys = dic.flatMap { $0.value.first == 60 ? $0.key : nil } 
//If you are having only one pair like that then simply access the first object from array 
print(filterKeys.first) 
//Other wise you can access the whole array 
print(filterKeys) 

注:如果你想检查ArrayDouble包含特定的值,而不是仅仅比较,你可以尝试这样的第一要素。

let filterKeys = dic.flatMap { $0.value.contains(60) ? $0.key : nil } 
//If you are having only one pair like that then simply access the first object from array 
print(filterKeys.first) 
//Other wise you can access the whole array 
print(filterKeys) 

编辑:如果你想检查数组包含> 60对于您可以使用contains(where:)对象。

let filterKeys = dic.flatMap { $0.value.contains(where: { $0 > 60}) ? $0.key : nil } 
+0

如果我想检查其他值怎么办?或者使条件像> 60?那可能吗? – kings077712

+0

@ kings077712你的意思是检查任何数组的值,并检查它是否> 60或不?或者只比较数组的第一个对象? –

+0

是的,而不只是比较第一个对象! – kings077712

1

您也可以使用第一(_其中:)

let item = dict.first { key, value in 
    value.contains(60) 
} 

let key = item?.key // this is your key Amber 

有了这个地方,你可以创建一个断言函数,你可以修改,以满足您的需要,

let predicate = { (num: Double) -> Bool in 
    num == 60.0 
} 

let dict = ["Olivia":[2.0, 0.0, 1.0, 3.0],"Amber":[60.0, 0.0, 0.0, 1.0]] 

let item = dict.first { key, value in 
    value.contains(where: predicate) 
} 

item?.key 

您可以根据需要更改谓词,

let predicate = {(num: Double) -> Bool in num > 60.0} // predicate to filter first key with values greater than 60.0 

let predicate = {(num: Double) -> Bool in num < 60.0} // predicate to filter first key with values greater than 60.0 

等。