Skip to content

Instantly share code, notes, and snippets.

@insanehunter
Last active August 29, 2015 14:15
Show Gist options
  • Save insanehunter/fe199aabb1334ec2e5ab to your computer and use it in GitHub Desktop.
Save insanehunter/fe199aabb1334ec2e5ab to your computer and use it in GitHub Desktop.
Versioned: monad-like structure for holding version number along with any value
public struct Versioned<T> {
public init(_ value: T) {
self.value = value
self.version = VersionGenerator.generateVersion()
}
public init(_ value: T, version: VersionGenerator.VersionType) {
self.value = value
self.version = version
}
public let value: T
public let version: VersionGenerator.VersionType
}
public func ==<T: Equatable>(a: Versioned<T>, b: Versioned<T>) -> Bool {
return a.version == b.version && a == b
}
public struct VersionGenerator {
public typealias VersionType = UInt64
private static func generateVersion() -> VersionType {
return ++VersionGenerator.currentVersion
}
private static var currentVersion: VersionType = 0
}
@insanehunter
Copy link
Author

Example usage:

let array = Versioned([1, 2, 3])
let indexOf3 = Versioned<Int>(2, version: array.version)

if array.version == indexOf3.version {
    // Index matches array!
    println(array.value[indexOf3.value])
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment