我试图创建的类型[NSObject:AnyObject]
扩展上迅速可变字典
这里可变字典扩展为[NSObject:AnyObject]
在斯威夫特一个不变的词典扩展语法:
extension Dictionary where Key:NSObject, Value:AnyObject {
func addSomething() {
// Fails
self["ExampleKey"] = "ExampleValue"
}
}
然而,这种情况下self
不能附加到,因为扩展工作在不可变的字典上。问题是缺少什么语法才能为专有可变字典进行扩展。
编辑:更新,以解决歧义
更新:
通过添加mutating
前缀addSomething
,我可以操作只可变dictionarys。好极了!然而,该功能仍不能正常工作
mutating func addSomething() {
// Error: Cannot subscript a value of type 'Dictionary<Key, Value>' with an index of type 'String'
self["ExampleKey"] = "ExampleValue"
}
如果我投"ExampleKey"
一个关键,我得到另一个错误:
mutating func addSomething() {
let key = "ExampleKey" as! Key
// Error: Ambiguous reference to member 'subscript'
self[key] = "ExampleValue"
}
仍在研究如何使这个简单的除了工作...
这是什么问题? –
或邮编不工作... –
或对您的问题的活动作出回应...高兴地帮助,并且我相信,如果您改进问题,downvoters会很乐意upvote –