ios - Swift 2.1 词典扩展

标签 ios swift macos dictionary

我希望编写一个 Swift 字典扩展,它将可靠地附加最终作为 URL 参数传递到 Web 请求中的相同数据。我尝试了各种技巧,但似乎都不起作用。

我得到的最接近的是:

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(...”这一行

有什么建议吗?提前致谢!

最佳答案

您只需要将您的字符串转换为!值还是一样! key 。此外,您已将您的方法声明为 mutating,因此您不需要返回任何内容。

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"

关于ios - Swift 2.1 词典扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35421820/

相关文章:

ios - Swift CollectionViewCell 的框架与其 CollectionView 不同

c++ - Makefile 不适用于 mac os x Mavericks

bash - 在 osx 上使用 xld 在命令行中分割提示音频文件

ios - 在单个 PFQuery 中从两个类中获取数据

ios - Firebase 和 Google Signin 给出重复符号错误

ios - 如何使用 UICollectionViewController 设置具有多个部分的 1 标题

java - 类 JavaLaunchHelper 在两个地方实现

ios - FSCalender 事件在 swift 中显示

ios - SetDelegate 导致 'unrecognized selector' 异常

ios - 为什么模拟器和我的 iPhone 之间的颜色不同?