2014-08-29 15 views
7

In java si potrebbe avere un metodo generico simile al seguente, in cui il tipo viene esplicitamente specificato e passato al metodo come argomento. È possibile con swift?Swift - Metodi generici

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); 

Quello che sto cercando di realizzare

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? Che ne dici di un commento? – aryaxt

+0

@Zaph L'ho fatto, e so già come scrivere funzioni generiche in modo rapido. Questo è un caso particolare in cui si passa anche il tipo di classe – aryaxt

+0

Sì, i voti bassi di drive-by senza una ragione non sono utili e piuttosto come quelli di una donnola. – zaph

risposta

7

T.Type è quello che ho dovuto usare, anche meglio di come Java gestisce questo

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

} 

Uso

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

In questo caso non sarebbe meglio un sovraccarico? Es .: 'func fetchObject (id: Int, tipo: User.Type) -> User', o anche meglio:' func fetchUser (id: Int) -> User'? – CouchDeveloper

+0

Questo è solo un esempio che ho fornito per spiegare il problema. Quello che sto cercando di ottenere è un metodo che accetta un dizionario e un tipo di classe, quindi basato su chiave/valori crea e popola un oggetto NSManagedObject e salva il contesto – aryaxt

+0

Quindi, perché non un dizionario di chiavi/chiusure? Potrebbe anche finire molto più elegante. – CouchDeveloper