esreli
esreli

Reputation: 5071

Swift 2.1 Dictionary extension

I'm hoping to write a Swift dictionary extension that will append the reliably same data that eventually gets passed into a web request as URL params. I've tried various tricks, none seem to work.

The closest i've gotten is:

extension Dictionary where Key: StringLiteralConvertible, Value: AnyObject {
    mutating func auth() -> Dictionary  {
        self.updateValue("2.0", forKey: "api")
        return self
    }
}

But this is still throwing the error:

Cannot invoke 'updateValue' with an argument list of type '(String, forKey:String)'

on the line that reads, "self.updateValue(..."

Any advice? Thanks in advance!

Upvotes: 1

Views: 295

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236538

You just need to cast your string as! Value or as! Key. Also you have declared your method as mutating so you don't need to return anything.

extension Dictionary {
    mutating func auth()  {
        updateValue("2.0" as! Value, forKey: "api" as! Key)
    }
}

var dic: [String:AnyObject] = [:]

print(dic)  // "[:]\n"
dic.auth()
print(dic)  // "["api": 2.0]\n"

Upvotes: 4

Related Questions