Skip to content

Instantly share code, notes, and snippets.

@aleclarson
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aleclarson/a5e3baeef1c475f09629 to your computer and use it in GitHub Desktop.
Save aleclarson/a5e3baeef1c475f09629 to your computer and use it in GitHub Desktop.
Reference
public enum ReferencePolicy {
case Strong, Weak
}
// Allows for a mix of strong and weak references inside Arrays and Dictionaries.
public class Reference <T: AnyObject> {
public var object: T! {
get { return _strong ?? _weak }
set {
if object === newValue { return }
if policy == .Strong { _strong = newValue }
else { _weak = newValue }
}
}
public var policy: ReferencePolicy {
didSet {
if policy != oldValue { swap(&_weak, &_strong) }
}
}
public var onDeinit: (Void -> Void)?
public init (_ object: T! = nil, _ policy: ReferencePolicy = .Strong) {
self.policy = policy
self.object = object
}
private var _strong: T!
private weak var _weak: T!
deinit { onDeinit?() }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment