Created
September 2, 2017 21:52
-
-
Save mklbtz/32ae2db43526e59f1f7d73f14cb5fd51 to your computer and use it in GitHub Desktop.
A type-safe String identifier for objects
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 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) | |
} | |
} |
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
protocol Record { | |
associatedtype ID = Identifier<Self> | |
var id: ID { get } | |
} | |
struct Order: Record { | |
let id: ID | |
} | |
let order = Order(id: "123") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Compatible with Swift 3.0 and higher