updateValue不适用于Dictionary [英] updateValue not working for Dictionary
问题描述
我正在使用Xcode中的Swift创建一个测试应用程序,我遇到了一个烦人的问题。我正在编写一个简单的类,它将使用Dictionary对象作为缓存。我的实现如下:
import Foundation
import UIKit
class ImageCache {
var dict:Dictionary< String,NSData>?;
init(){
dict =字典< String,NSData>();
}
func exists(id:String) - > Bool {
return dict!.indexForKey(id)!== nil;
}
func getImage(id:String) - > UIImage的? {
if(!exists(id)){
return nil;
}
return UIImage(data:(dict!)[id]);
}
func setData(id:String,data:NSData){
dict!.updateValue(data,forKey:id);
}
}
问题是最后一个方法,Xcode说找不到成员'UpdateValue'。这很奇怪,因为代码提示似乎很好地显示:
但是当我尝试编译:
这可能是Xcode中的错误吗?或者我错过了一些超级明显的东西?
这不是编译器中的错误或怪癖。
它是如何实现的(可能有缺陷)
发生了什么是可选
将字典
存储为不可变对象(使用 let
也许)所以即使可选
它是可变的,您不能直接修改底层的字典
对象(不重新分配Optional对象)
updateValue(forKey:)
是变异方法,你不能在不可变对象上调用它,因此
您可以通过执行
var d =字典!
d.updateValue(data,forKey:id)
因为你将字典复制到另一个可变变量,然后是可变的,并且能够调用变异方法
,但没有 dict = d
,您的更改不会应用于 dict
,因为字典
是值类型,它使每个作业复制
I'm creating a test app using Swift in Xcode, and I've run into an annoying issue. I'm writing a simple class that will act as a cache using a Dictionary object. My implementation is below:
import Foundation
import UIKit
class ImageCache {
var dict:Dictionary<String,NSData>?;
init() {
dict = Dictionary<String,NSData>();
}
func exists(id:String) -> Bool {
return dict!.indexForKey(id)!==nil;
}
func getImage(id:String) -> UIImage? {
if(!exists(id)) {
return nil;
}
return UIImage(data: (dict!)[id]);
}
func setData(id:String, data:NSData) {
dict!.updateValue(data, forKey: id);
}
}
The issue is in the last method, with Xcode stating "Could not find member 'UpdateValue'". This is weird, because the code hint seems to show it just fine:
But when I try to compile:
Could this potentially be a bug in Xcode? Or am I missing something super-obvious?
this is not a bug or a quirk in the compiler.
it is how Optional
implemented (which may be flawed or not)
what happened is that the Optional
store the Dictionary
as immutable object (with let
perhaps). So even Optional
it is mutable, you can't modify the underlying Dictionary
object directly (without reassign the Optional object).
updateValue(forKey:)
is mutating method, you can't call it on immutable object and hence the error.
you can workaround it by doing
var d = dict!
d.updateValue(data, forKey: id)
because you copy the dictionary to another mutable variable, which then is mutable and able to call mutating method on it
but without dict = d
, your change won't be applied on dict
because Dictionary
is value type, it makes copy on every assignment
这篇关于updateValue不适用于Dictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!