kings077712
kings077712

Reputation: 55

Swift dictionary get the value without access or knowing the key

I am using the dictionary and trying to get the value without knowing or accessing the key. It is my dictionary look like "Olivia":[2.0, 0.0, 1.0, 3.0],"Amber":[60.0, 0.0, 0.0, 1.0] It is a [String: ArrayDouble] dictionary but I want to check if there is any value in the Value(ArrayDouble) which contain 60.0 then get display the Key for that value. What I was tried to do is :

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

  if (number== value[0]){

    print(...the key)

  }else{

}

Upvotes: 1

Views: 1827

Answers (2)

Sandeep
Sandeep

Reputation: 21134

You could also use first(_ where:),

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

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

With this in place, you could create a predicate function which you could modify to suit your need,

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

You could change the predicate as you require,

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

and so on.

Upvotes: 2

Nirav D
Nirav D

Reputation: 72410

You can go like this.

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)

Note: If you want to check that ArrayDouble contains specific value instead of just comparing first element you can try like this.

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)

Edit: If you want to check arrays contains object with > 60 for that you can use contains(where:).

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

Upvotes: 1

Related Questions