Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to extend Swift Dictionary of where K:String and V:String

I was thinking the following syntax:

extension Dictionary where Key:String,Value:String{
    func addIfNew(key:String,value:String){
      print("new item added: \(key) with value: \(value)")
    }
}

For example: the function would log any new added data

like image 460
Ilan Levy Avatar asked Mar 05 '16 12:03

Ilan Levy


1 Answers

This should be enough ...

protocol P {}
extension String: P {}
extension Dictionary where Key:P, Value:P {
    func addIfNew(key:String, value:String){
        print("new item added: \(key) with value: \(value)")
    }
}

let d:[String:String] = [:]

don't make other types conforming to P and you are fine

in Swift3

extension Dictionary where Key == String, Value == String {
    func addIfNew(key:String, value:String){
        print("new item added: \(key) with value: \(value)")
    }
}
let d:[String:String] = [:]
d.addIfNew(key: "a", value: "A")
like image 187
user3441734 Avatar answered Oct 16 '22 13:10

user3441734