仅将特定类型作为参数传递给函数

时间:2016-05-18 17:30:39

标签: swift

我有一个重复大约8-9次的函数,我正在尝试减少冗余。是否可以创建一个函数,它接受spefic类型并使用json对象返回一个initlizated类型的数组被送了。

当前功能

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

期望的功能

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
}

1 个答案:

答案 0 :(得分:1)

初始化T的实例,就像任何已知类的实例一样,可以使用任何初始值设定项。要了解您的选项,通常需要以某种形式约束T。我通常采用的方法是定义一个protocol,我关心传递给函数的所有类型都采用。在您的情况下,您可以在protocol中添加特定的初始值设定项。然后约束T为该类型:

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]
    }
}

限制泛型类型可能比我显示的更复杂,因此我建议您查看Type Constraints Generics章节的The Swift Programming Language部分以获取更多信息。< / p>