Skip to content

Instantly share code, notes, and snippets.

@marksands
Last active July 2, 2018 17:42
Show Gist options
  • Save marksands/c05642ed600f38091411df6c7dabb56c to your computer and use it in GitHub Desktop.
Save marksands/c05642ed600f38091411df6c7dabb56c to your computer and use it in GitHub Desktop.
playing with dynamicMemberLookup
class Database {
private static let users = [User(id: 1, name: "Jane"), User(id: 2, name: "Clara"), User(id: 3, name: "Sandy")]
static func find(id: Int) -> User? {
return users.first(where: { $0.id == id })
}
static func find(name: String) -> User? {
return users.first(where: { $0.name == name })
}
}
@dynamicMemberLookup
public class Queryable<T> { }
extension Queryable where T == User.Type {
public subscript(dynamicMember member: String) -> (Any) -> User? {
return { arg in
if let id = arg as? Int {
return Database.find(id: id)
} else if let name = arg as? String {
return Database.find(name: name)
} else {
return nil
}
}
}
}
public protocol QueryProviding { }
extension QueryProviding {
public typealias QueryBase = Self.Type
public static var query: Queryable<QueryBase> {
return Queryable<QueryBase>()
}
}
public struct User {
public let id: Int
public let name: String
}
extension User: QueryProviding { }
User.query.find_by_id(42)
User.query.find_by_name("Jane")
User.query.find_by_id(3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment