Skip to content

Instantly share code, notes, and snippets.

@tomlokhorst
Created September 12, 2018 14:14
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 tomlokhorst/cb634deeea5793206c033439f814c4b9 to your computer and use it in GitHub Desktop.
Save tomlokhorst/cb634deeea5793206c033439f814c4b9 to your computer and use it in GitHub Desktop.
// This protocol should be in the Standard library
protocol Newtypeable {
associatedtype Original
init(value: Original)
var value: Original { get }
}
// The Standard libary can include useful extensions like this one
extension Newtypeable where Original: Hashable {
func hash(into hasher: inout Hasher) {
value.hash(into: &hasher)
}
var hashValue: Int {
return value.hashValue
}
}
// Similarily, third-party libraries can include a Newtypable extension for their own protocols
// Declare RecordId using a newtype
newtype RecordId = Int
// Behind the scenes, this generates something like this
struct RecordId: Newtypeable {
let value: Int
}
// Users can opt-in to the a protocol with a single line
extension RecordId: Hashable {}
// Alternatively, a custom implementation can be provided
extension RecordId: Hashable {
var hashValue: Int { return 42 }
}
// RecordId can be used as a key in a dictionary
let dictionary: [RecordId: String] = [:]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment