How do i get a Value for Key? - Why is method not working?

时间:2015-11-12 12:01:13

标签: string swift dictionary swift2

I have a dictionary containing String keys and String values.

To get the value for a specific key, i have written a method.

func getValueForKey(key: String) -> String? {
   for (value, keys) in myDictionary {
      if (keys.containsString(key)){
         return value
      }
   }
   return nil
}

I use the same logic to get the key for a certain value and its working perfectly.

I know that there are some other ways on stackoverflow to get the key but I want to know why my method is not working?

They are both of type String and Dictionary.values as well as Dictionary.keys are both containers including the values or keys.

2 个答案:

答案 0 :(得分:3)

You are referring key and value wrongly.

func getValueForKey(key: String) -> String? {
   for (keys, value) in myDictionary {
      if (keys.containsString(key)){
         return value
      }
   }
   return nil
}

Please note that you can access myDictionary[key]

答案 1 :(得分:1)

func getValueForKey(searchKey: String) -> String? {
  for (value, key) in myDictionary {
    if (key == searchKey){
     return value
    }
  }
return nil
}

Please try the code above. In the for loop you will get every time a single key, value pair. You should compare with == and not contain