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

标签 swift

我有一个重复大约 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/

相关文章:

ios - 更改 AVPlayer 当前项目(项目 url)并开始播放

swift - inout String 不能转换为 Swift 3 范围内的 String

swift - Swift 中使用的 ~>(波浪号大于)运算符是什么?

ios - Swift 和 Sprite 套件接触不正确

ios - 如何从日期(2018-09-28 09 :42:00 +0000 ) without time in Date format - iOS swift?)中提取日、月和年(dd-MM-yyyy)

ios - 平移手势无法正常工作

swift - 使用 openTok 发送消息

ios - 在 Swift 中以编程方式呈现模态视图 Controller

ios - 如何在 iOS 中以编程方式检查日历订阅的 ics feed

ios - 条件绑定(bind) : if let error – Initializer for conditional binding must have Optional type