In java you could have a generic method similar to below, where the type is explicitly specified and passed to the method as an argument. Is this possible with 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);
What I'm trying to achieve
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
}
Swift 4 language provides 'Generic' features to write flexible and reusable functions and types. Generics are used to avoid duplication and to provide abstraction. Swift 4 standard libraries are built with generics code. Swift 4s 'Arrays' and 'Dictionary' types belong to generic collections.
Generic code enables you to write flexible, reusable functions and types that can work with any type, subject to requirements that you define. You can write code that avoids duplication and expresses its intent in a clear, abstracted manner.
The placeholder type T is used in the function declaration. It tells Swift that this function can find any item in any array, as long as the foundItem and items in the array are of the same type. This makes sense — you want to look for a T value in an array of T values.
T.Type
is what I had to use, even better than how java handles this
public func fetchObject<T> (id: Int, type: T.Type) -> T? {
}
Usage
var myClass = fetchObject(5, MyClass.self)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With