2014-08-29 37 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