Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Generic methods

Tags:

generics

swift

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
}
like image 608
aryaxt Avatar asked Aug 29 '14 15:08

aryaxt


People also ask

What are generic types in Swift?

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.

What is generic function in Swift?

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.

What is T type Swift?

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.


1 Answers

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)
like image 148
aryaxt Avatar answered Nov 02 '22 22:11

aryaxt