【发布时间】:2014-10-23 16:12:11
【问题描述】:
在 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?评论如何?
-
@Zaph 我做到了,而且我已经知道如何在 swift 中编写通用函数。这是一种特殊情况,您还可以传递类类型
-
是的,无缘无故的直接投票没有帮助,更像是黄鼠狼。
-
您的问题是专门针对 NSManagedObject 的子类的吗?那么这个stackoverflow.com/questions/24834753/… 或stackoverflow.com/questions/24537238/… 可能会有所帮助。
-
是的,我链接的问题/答案也是关于泛型函数的,并且都演示了如何将类型传递给函数。