Last active
March 14, 2018 22:22
-
-
Save gonzalonunez/d180f76d9d75b4c3cb47e7bc0df15c50 to your computer and use it in GitHub Desktop.
Routing Problem
This file contains hidden or 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
import Foundation | |
// This is the equivalent to `CellDescriptor` https://talk.objc.io/episodes/S01E26-generic-table-view-controllers-part-2 | |
struct Handler { | |
// This is the problem... What I really need is `type` to be a concrete type that conforms to Decodable. | |
// I don't want to force users to have to conform to some arbitrary class of mine. | |
// In the case of UITableViewCell this worked out fine bc of the already-required inheritance. Is there a work around? | |
let type: Decodable.Type | |
let handle: (Decodable) -> Void | |
init<T: Decodable>(handler: @escaping (T) -> Void) { | |
type = T.self | |
handle = { codable in | |
handler(codable as! T) | |
} | |
} | |
} | |
// Here's where I set up the (simplified) routing aka try to store functions in a dictionary keyed by "endpoints": | |
var handlers = [String: Handler]() | |
func register<T: Decodable>( | |
endpoint: String, | |
with handle: @escaping (T) -> Void) | |
{ | |
handlers[endpoint] = Handler(handler: handle) | |
} | |
// I'd like to do something like this at the callsite: | |
register(endpoint: "hello") { (object: String) in | |
// handle receiving messages for this endpoint here | |
} | |
// Here's what I'd like to do once I have data and know the endpoint: | |
func didReceive(data: Data, for endpoint: String) throws { | |
guard let handler = handlers[endpoint] else { return } | |
let object = try JSONDecoder().decode(handler.type, from: data) // Cannot invoke 'decode' with an argument list of type '(Decodable.Type, from: Data)'. Expected an argument list of type '(T.Type, from: Data)' | |
handler.handle(object) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment