Swift - general methods

In java, you may have a general method similar to the one below, where the type is explicitly specified and passed to the method as an argument. Is this possible with a quick one?

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 am i 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 } 
+7
generics swift
source share
1 answer

T.Type is what I had to use, even better than java handles this

 public func fetchObject<T> (id: Int, type: T.Type) -> T? { } 

Using

 var myClass = fetchObject(5, MyClass.self) 
+7
source share

All Articles