Avatar
swiftbot BOT 6/5/2018 7:43 AM
(edited)
Author icon
koher
struct Weak<Value : AnyObject> { weak var value: Value? { didSet { print("Weak.value didSet") } } init(_ value: Value) { self.value = value } } extension Weak : Equatable where Value : Equatable { static func ==(lhs: Weak<Value>, rhs: Weak<Value>) -> Bool { return lhs.value == rhs.value } } extension Weak : Hashable where Value : Hashable { var hashValue: Int { return value?.hashValue ?? 0 } } class Foo : Hashable { static func ==(lhs: Foo, rhs: Foo) -> Bool { return lhs === rhs } var hashValue: Int { return ObjectIdentifier(self).hashValue } } var dict: [Weak<Foo>: Int] = [:] var weak1: Weak<Foo>! var weak2: Weak<Foo>! do { let foo1 = Foo() weak1 = Weak(foo1) dict[weak1] = 111 print("weak1: \(weak1)") let foo2 = Foo() weak2 = Weak(foo2) dict[weak2] = 222 print("weak2: \(weak2)") for (key, value) in dict { print("\(key) -> \(value)") } print("dict[weak1]: \(String(describing: dict[weak1]))") print("dict[weak2]: \(String(describing: dict[weak2]))") } print("---") print("weak1: \(weak1)") print("weak2: \(weak2)") for (key, value) in dict { print("\(key) -> \(value)") } print("dict[weak1]: \(String(describing: dict[weak1]))") print("dict[weak2]: \(String(describing: dict[weak2]))")
Version:
swift-4.1.1-RELEASE
Output:
weak1: Optional(main.Weak<main.Foo>(value: Optional(main.Foo))) weak2: Optional(main.Weak<main.Foo>(value: Optional(main.Foo))) Weak<Foo>(value: Optional(main.Foo)) -> 222 Weak<Foo>(value: Optional(main.Foo)) -> 111 dict[weak1]: Optional(111) dict[weak2]: Optional(222) --- weak1: Optional(main.Weak<main.Foo>(value: nil)) weak2: Optional(main.Weak<main.Foo>(value: nil)) Weak<Foo>(value: nil) -> 222 Weak<Foo>(value: nil) -> 111 dict[weak1]: nil dict[weak2]: nil
Error:
7:43 AM