Reputation: 77596
In java you could have a generic method similar to below, where the type is explicitly specified and passed to the method as an argument. Is this possible with swift?
public T fetchObject(Class<T> clazz, int id) {
// My table name is the same as class name
// So based on the generic type passed to method I want to fetch that record.
}
User user = fetchObject(User.class, 5);
What I'm trying to achieve
public func fetchObject (id: Int /* Somehow pass the type */) -> T? {
// I need a way to know what class type has to be used with this generic method
// Create NSEntityDescription based on the generic class passed
// managedObjectContext getExistingObjectById
}
Upvotes: 15
Views: 7113
Reputation: 77596
T.Type
is what I had to use, even better than how java handles this
public func fetchObject<T> (id: Int, type: T.Type) -> T? {
}
Usage
var myClass = fetchObject(5, MyClass.self)
Upvotes: 20