kye kye - 7 months ago 17
Swift Question

Pass only specific types as argument to function

I have a function which is being repeated about 8-9 times and I'm trying to cut down on redundancy.Is it possible to create a function which take spefic types and returns an array of the initlizated type using the json object being sent.

Current function

static func initArray(json: JSON)-> [Event]{
var array = [Event]()
array.append(Event.init(json: $0.1))
return array

Desired function

static func initArray<T> (type: T, json: JSON)-> [T]{
var array = [T]()
//I get stuck here im not too sure how to initlize the type
//Thats why im wondering if it's possible to pass speific types
//to the function
return array


You initialize an instance of T just like an instance of any known class, with whatever initializers are available to it. To know what your options are, you generally need to constraint T in some form. The way I typically go about this is to define a protocol that all the types I care about passing to the function adopt. In your case you would put specific initializers in your protocol. Then constraint T to be of that type:

protocol SomeProtocol {
    init(json: JSON)

class someClass {
    static func initArray<T:SomeProtocol>(type: T, json: JSON) -> [T] {
        // Create your objects, I'll create one as an example
        let instance = T.init(json: json)

        return [instance]

Constraining generic types can be more complex than what I've shown, so I'd recommend checking out the Type Constraints section of the Generics chapter of The Swift Programming Language for more information.