Muzahidul
6/21/2015 - 5:47 AM

Swift dictionary extension to get the values for multiple keys

Swift dictionary extension to get the values for multiple keys

extension Dictionary {
    func valuesForKeys(keys: [Key])->[Value?]{
        var result = [Value?]()
        result.reserveCapacity(keys.count)
        for key in keys{
            result.append(self[key])
        }
        return result
    }
}

// Implementation
var dic = [
            "A" : "Apple",
            "B" : "Banana",
            "C" : "Clemon",
            "D" : "Date"
        ]
let values = dic.valuesForKey(["A","D"])
// Output : [Apple,Date]