Here's the standard boilerplate weak container in Swift.
struct Weak<T: AnyObject> {
weak var value: T?
init(value: T) {
self.value = value
}
}
It works well unless you want T
to be a protocol, e.g.,
protocol ImplementationHiding: class {}
class Implementation: ImplementationHiding {}
let w = Weak(value: Implementation() as ImplementationHiding)
This does not compile, sadly. The only way I've found to get it work is to introduce @objc
on the protocol:
@objc protocol ImplementationHiding {}
The only way I've found around this is pretty ugly, since it throws out compile-time safety.
struct Weak<T> {
private let get: () -> T?
init(value: AnyObject, type: T.Type = T.self) {
get = { [weak value] in value as! T? }
}
var value: T? {
return get()
}
}
How can I create Weak
with a native Swift protocol as T
?