WeakDictionary
Swift 中的一个简单(强键/弱值)字典和(弱键/弱值)字典实现。
Apple 提供了一个现有的实现,它不是类型安全的,但您可能更喜欢使用它。例如,NSMapTable 的优点在于,您无需手动触发旧 nil 引用清理。
WeakDictionary
- 存储在
WeakDictionary
中的值不会被保留 - 键必须实现
Hashable
协议 weakDictionary
将创建一个新的WeakDictionary
,并删除任何孤儿值引用weakKeyDictionary
将创建一个新的WeakKeyDictionary
,并删除任何孤儿值引用,这将仅当键是类类型时才有效dictionary
将创建一个新的 Swift 字典,并排除任何已失效的值引用reap
将删除可变字典中的任何孤儿值引用
var dictionary = WeakDictionary<String, ExampleValue>()
var value: ExampleValue? = ExampleValue()
dictionary["key"] = value
print("\(dictionary["key"] != nil ? "has value" : "value missing")")
//prints: has value
value = nil
print("\(dictionary["key"] != nil ? "has value" : "value missing")")
//prints: value missing
private class ExampleValue { }
WeakKeyDictionary
- 存储在
WeakKeyDictionary
中的键和值不会被保留 - 键必须实现
Hashable
协议 weakDictionary
将创建一个新的WeakDictionary
,并删除任何孤儿值引用weakKeyDictionary
将创建一个新的WeakKeyDictionary
,并删除任何孤儿值引用dictionary
将创建一个新的 Swift 字典,并排除任何已失效的键或值引用- 代码
reap
会移除所有可变字典中的孤立键或值引用 - 可选地,可以通过使用
WeakKeyDictionary(valuesRetainedByKey: true)
来保留键的值, Values 只有在键的引用被回收后才会被释放
var dictionary = WeakKeyDictionary<ExampleKey, ExampleValue>()
var transientKey: ExampleKey = ExampleKey(name: "value")
let retainedValue: ExampleValue? = ExampleValue()
dictionary[transientKey] = retainedValue
print("\(dictionary[transientKey] != nil ? "an example exits" : "no example exits")")
//prints: an example exits
transientKey = ExampleKey(name: "anothervalue")
let oldKey = ExampleKey(name: "value")
print("\(dictionary[oldKey] != nil ? "an example exits" : "no example exits")")
//prints: no example exits
print("number of item in dictionary \(dictionary.count)")
//prints: number of item in dictionary 1
//This is because nil key/value references are not automatically nullified when the key or value is deallocated
print("number of item in reaped dictionary \(dictionary.weakKeyDictionary().count)")
//prints: number of item in reaped dictionary 0
//Reaping the dictionary removes any keys without values and values not referenced by any key
private class ExampleValue { }
private class ExampleKey: Hashable {
let value: String
init(name: String) {
value = name
}
public static func == (lhs: ExampleKey, rhs: ExampleKey) -> Bool {
return lhs.value == rhs.value
}
public var hashValue: Int {
return value.hash
}
}