Last active
August 29, 2015 14:07
-
-
Save aleclarson/a5e3baeef1c475f09629 to your computer and use it in GitHub Desktop.
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
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