Home > Software engineering >  Swift dictionary: return values for all keys containing a prefix
Swift dictionary: return values for all keys containing a prefix

Time:08-16

I have a Dictionary (Swift 5)

dict = ["ken" : 0, "Kendall" : 1, "kenny" : 2, "Sam" : 0, "Ben" : 3]

I'm trying to build a search function that returns the values for all keys/names containing the prefix

so if the input is "ken" it should return the values for the keys/names "ken", "Kendall", and "Kenny" because they all contain "ken" in their first 3 characters.

func search( string : String, dict : [String:Int] )->[Int] { }

returns [0,1,2]

CodePudding user response:

let dict = ["ken" : 0, "Kendall" : 1, "kenny" : 2, "Sam" : 0, "Ben" : 3]

let result = dict.filter( { $0.key.lowercased().hasPrefix("ken") } ).values

CodePudding user response:

This is the answer: we filter the dict for the keys containing the input and return all the values

func search( string : String, dict : [String:Int] )->[Int] {

let temp = dict.filter { key , value in
        
return key.contains(string)

}
    

return Array(temp.values)
}
  • Related