-
-
Save tomlokhorst/cb634deeea5793206c033439f814c4b9 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
// 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 |
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
// 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