Skip to content

Instantly share code, notes, and snippets.

@VAndrJ
Created January 24, 2019 08:47
Show Gist options
  • Save VAndrJ/57946990e029163af5ba2d5519664e2e to your computer and use it in GitHub Desktop.
Save VAndrJ/57946990e029163af5ba2d5519664e2e to your computer and use it in GitHub Desktop.
struct TypedIdentifier<T>: Equatable, Codable, ExpressibleByIntegerLiteral, CustomStringConvertible, RawRepresentable {
let rawValue: Int
var description: String {
return "\(rawValue)"
}
init?(rawValue: Int) {
self.rawValue = rawValue
}
init(integerLiteral value: Int) {
self.rawValue = value
}
}
protocol Identifiable {
typealias Identifier = TypedIdentifier<Self>
var id: Identifier { get }
}
struct Post: Equatable, Codable, Identifiable {
let id: Identifier
let title: String
let body: String
}
struct Hotel: Equatable, Codable, Identifiable {
let id: Identifier
let name: String
let description: String
}
func orderRoomInHotel(withId id: TypedIdentifier<Hotel>) { }
let somePost = Post(id: 1, title: "Title", body: "Body")
print(somePost)
// Post(id: 1, title: "Title", body: "Body")
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let jsonData = try! encoder.encode(somePost)
print(String(data: jsonData, encoding: .utf8)!)
/*
{
"id" : 1,
"title" : "Title",
"body" : "Body"
}
*/
orderRoomInHotel(withId: somePost.id)
// Error: Cannot convert value of type 'Post.Identifier' (aka 'TypedIdentifier<Post>') to expected argument type 'TypedIdentifier<Hotel>'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment