2014-08-29 31 views
7

在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 
} 
+0

更好-1?如何评论? – aryaxt 2014-08-29 16:21:25

+0

@Zaph我做了,我已经知道如何在swift中编写泛型函数。这是一个特殊的情况,你也通过类型 – aryaxt 2014-08-29 16:32:49

+0

是的,没有理由的驱动器倒票没有帮助,而是黄鼠狼喜欢。 – zaph 2014-08-29 16:36:25

回答

7

T.Type是什么,我不得不用,甚至比Java是如何处理这个

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

} 

使用

var myClass = fetchObject(5, MyClass.self) 
+0

在这种情况下,一组重载不会更好吗?例如:'func fetchObject(id:Int,type:User.Type) - > User',甚至更好:'func fetchUser(id:Int) - > User'? – CouchDeveloper 2014-08-29 17:19:32

+0

这只是我提供的一个例子来解释问题。我实际上想要实现的是一种方法,它需要一个字典和一个类的类型,然后基于它创建的键/值,并填充一个NSManagedObject并保存上下文 – aryaxt 2014-08-29 17:21:31

+0

然后,为什么不是一个键/闭包字典?最终可能会更加优雅。 – CouchDeveloper 2014-08-29 17:23:11