Swift - 通用方法

时间:2014-08-29 15:50:54

标签: generics swift

在java中,您可以使用类似于下面的泛型方法,其中显式指定类型并将其作为参数传递给方法。这可以用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);

我想要实现的目标

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
}

1 个答案:

答案 0 :(得分:14)

T.Type是我必须使用的,甚至比java处理这个

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

}

用法

var myClass = fetchObject(5, MyClass.self)