我有一个函数,被重复了8-9次,我试图减少redundancy.Is,可以创建一个函数,该函数使用发送的json对象返回一个特定类型的数组。
电流函数
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
}发布于 2016-05-18 17:41:46
您可以像任何已知类的实例一样初始化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]
}
}https://stackoverflow.com/questions/37306495
复制相似问题