Created
February 5, 2021 14:40
-
-
Save evnik/c6de198282b00921666bf83e19ccd865 to your computer and use it in GitHub Desktop.
Testing hashable weak reference
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
class WeakWrapper: Hashable { | |
private(set) weak var value: AnyObject? | |
init(_ value: AnyObject) { | |
self.value = value | |
} | |
static func == (lhs: WeakWrapper, rhs: WeakWrapper) -> Bool { | |
lhs.value === rhs.value | |
} | |
func hash(into hasher: inout Hasher) { | |
value?.pointerValue?.hash(into: &hasher) | |
} | |
} | |
class Test { } | |
func createSet() -> Set<WeakWrapper> { | |
var result = Set<WeakWrapper>() | |
let v1 = Test() | |
result.insert(WeakWrapper(v1)) | |
let v2 = Test() | |
result.insert(WeakWrapper(v2)) | |
let v3 = Test() | |
result.insert(WeakWrapper(v3)) | |
return result | |
} | |
var set = createSet() | |
let hasNilValues = set.contains { $0.value == nil } | |
if hasNilValues { | |
print("Found nil values") | |
let v4 = Test() | |
set.insert(WeakWrapper(v4)) | |
print("Inserted") | |
} else { | |
print("No nil values") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment