我有一个重复大约 8-9 次的函数,我正在尝试减少冗余。是否可以创建一个采用特定类型并使用 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
}
最佳答案
您可以像任何已知类的实例一样初始化 T
的实例,并使用任何可用的初始化程序。要知道您的选择是什么,您通常需要以某种形式约束 T
。我通常处理此问题的方法是定义一个协议(protocol),我关心传递给函数的所有类型都采用该协议(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的章节了解更多信息。
关于swift - 仅将特定类型作为参数传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37306495/