Skip to content

Instantly share code, notes, and snippets.

@Cellane
Created June 6, 2018 07:21
Show Gist options
  • Save Cellane/63fb9fa16cb5ec9de6e5e0778ebbf093 to your computer and use it in GitHub Desktop.
Save Cellane/63fb9fa16cb5ec9de6e5e0778ebbf093 to your computer and use it in GitHub Desktop.
protocol Query {
associatedtype QueryType
var codingKey: String { get } // set?
}
private class _AnyQueryBase<QueryType>: Query {
var codingKey: String {
get { fatalError("Must override") }
}
init() {
guard type(of: self) != _AnyQueryBase.self else {
fatalError("Must subclass")
}
}
}
private final class _AnyQueryBox<ConcreteQuery: Query>: _AnyQueryBase<ConcreteQuery.QueryType> {
var concrete: ConcreteQuery
override var codingKey: String {
get { return concrete.codingKey }
}
init(_ concrete: ConcreteQuery) {
self.concrete = concrete
}
}
final class AnyQuery<QueryType>: Query {
private let box: _AnyQueryBase<QueryType>
var codingKey: String {
get { return box.codingKey }
}
init<Concrete: Query>(_ concrete: Concrete) where Concrete.QueryType == QueryType {
box = _AnyQueryBox(concrete)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment