Created
September 4, 2017 22:28
-
-
Save mklbtz/c20c669fe00f017739854b2a72bd04c5 to your computer and use it in GitHub Desktop.
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
/// Useful for maintaining a strong reference to | |
/// something which would otherwise be deinitialized. | |
public final class Token<A> { | |
public let id: A | |
private let dispose: (A) -> Void | |
/// Create a new token | |
/// | |
/// - Parameters: | |
/// - id: A unique identifier for this token. | |
/// - dispose: Should keep a reference to | |
/// any object you want to persist. When this | |
/// Token is destroyed, this function is called, | |
/// allowing you to cleanup that object. | |
public init(_ id: A, dispose: @escaping (A) -> Void) { | |
self.id = id | |
self.dispose = dispose | |
} | |
deinit { dispose(id) } | |
/// Make an iterator of Tokens based on a sequence of ids. | |
/// | |
/// - Parameters: | |
/// - sequence: The sequence of ids to use for the Tokens. | |
/// - dispose: The dispose function to use for all Tokens. Recieves ids as parameters. | |
static func sequence<S>(from sequence: S, dispose: @escaping (S.Element) -> Void) -> AnyIterator<Token<S.Element>> where S: Sequence { | |
var ids = sequence.makeIterator() | |
return AnyIterator { | |
ids.next().map { Token<S.Element>($0, dispose: dispose) } | |
} | |
} | |
} | |
extension Token where A: Equatable { | |
public static func ==(lhs: Token, rhs: Token) -> Bool { | |
return lhs.id == rhs.id | |
} | |
} | |
extension Token where A: Hashable { | |
public var hashValue: Int { | |
return id.hashValue | |
} | |
} | |
extension Token where A: Comparable { | |
public static func < (lhs: Token, rhs: Token) -> Bool { | |
return lhs.id < rhs.id | |
} | |
public static func > (lhs: Token, rhs: Token) -> Bool { | |
return lhs.id > rhs.id | |
} | |
public static func <= (lhs: Token, rhs: Token) -> Bool { | |
return lhs.id <= rhs.id | |
} | |
public static func >= (lhs: Token, rhs: Token) -> Bool { | |
return lhs.id >= rhs.id | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment