Skip to content

Instantly share code, notes, and snippets.

@mklbtz
Created September 2, 2017 21:52
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 mklbtz/32ae2db43526e59f1f7d73f14cb5fd51 to your computer and use it in GitHub Desktop.
Save mklbtz/32ae2db43526e59f1f7d73f14cb5fd51 to your computer and use it in GitHub Desktop.
A type-safe String identifier for objects
/// Useful as a type-safe String identifier for objects, records, etc.
/// Generic type A is the type of the object being "identified".
public struct Identifier<A>: Equatable, Hashable, Comparable {
public let string: String
public init(_ string: String) {
self.string = string
}
public var hashValue: Int {
return debugDescription.hashValue
}
public static func ==<A>(lhs: Identifier<A>, rhs: Identifier<A>) -> Bool {
return lhs.string == rhs.string
}
public static func < <A>(lhs: Identifier<A>, rhs: Identifier<A>) -> Bool {
return lhs.string < rhs.string
}
}
extension Identifier: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self.string = value
}
}
extension Identifier: CustomStringConvertible {
public var description: String {
return string
}
}
extension Identifier: CustomDebugStringConvertible {
public var debugDescription: String {
return "\(Identifier.self)(\(string))"
}
}
extension Identifier: CustomPlaygroundQuickLookable {
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return PlaygroundQuickLook.text(string)
}
}
protocol Record {
associatedtype ID = Identifier<Self>
var id: ID { get }
}
struct Order: Record {
let id: ID
}
let order = Order(id: "123")
@mklbtz
Copy link
Author

mklbtz commented Sep 3, 2017

Compatible with Swift 3.0 and higher

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