Last active
February 26, 2020 13:32
-
-
Save Gatada/772f2e797c87c204ab956f5c247181df to your computer and use it in GitHub Desktop.
Trying to implement a reapable array with weak references.
This file contains 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 Weak<T: AnyObject> { | |
weak var value: T? | |
init (value: T) { | |
self.value = value | |
} | |
} | |
class Stuff: CustomStringConvertible, Equatable { | |
static func == (lhs: Stuff, rhs: Stuff) -> Bool { | |
guard let lv = lhs.value, let rv = rhs.value else { | |
return false | |
} | |
return lv == rv | |
} | |
var value: String? | |
init(value: String?) { | |
self.value = value | |
} | |
var description: String { | |
"Stuff: \(value ?? "nil")" | |
} | |
} | |
let one = Stuff(value: "One") | |
let two = Stuff(value: "Two") | |
func setup() -> [Weak<Stuff>] { | |
let three = Stuff(value: "Three") | |
let weakly: [Weak<Stuff>] = [Weak(value: one), Weak(value: two), Weak(value: three)] | |
for w in weakly { | |
print((w.value)?.description as Any) | |
} | |
return weakly | |
} | |
extension Array where Element: Weak<Stuff> { | |
mutating func reap () { | |
self = self.filter { nil != $0.value } | |
} | |
} | |
var weakly: [Weak<Stuff>] = setup() | |
for w in weakly { | |
print((w.value)?.description as Any) | |
} | |
weakly.reap() | |
for w in weakly { | |
print((w.value)?.description as Any) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment