2016-02-16 78 views
1

我希望能够编写一个Swift字典扩展,它会将最终得到的可靠数据作为URL参数附加到Web请求中。我尝试了各种技巧,似乎没有任何工作。Swift 2.1字典扩展

我已经得到最接近的是:

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

但这仍然引发错误:

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

上读取行, “self.updateValue(...”

有什么建议?在此先感谢!

+0

'self.updateValue(“2.0”as StringLiteralConvertible,forKey:“api”as AnyObject)'help?我认为它的类型不匹配,但我远离办公室mac。 – Ajwhiteway

回答

4

你只需要投你的字符串!值或!关键。也可为y你已经宣布你的方法是变异的,所以你不需要返回任何东西。

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"