generics数组的swift扩展

时间:2017-11-02 03:01:19

标签: swift generics extension-methods

我想返回[S:M]类型,但Xcode会提醒Single argument function types require parentheses,有没有办法解决这个问题,请帮助我,谢谢

extension Array {
    func merge<S, M>() where Element == [S:M] -> [S:M] {
        var res: [S:M] = [:]
        forEach { (element) in
            element.forEach({ (obj) in
                res[obj.key] = obj.value
            })
        }
        return res
    }
}

1 个答案:

答案 0 :(得分:1)

-> [S:M]需要放在where子句之前。

extension Array {
  func merge <S, M> () -> [S: M] where Element == [S: M] {
    var res: [S: M] = [:]

    self.forEach { element in
      element.forEach { obj in
        res[obj.key] = obj.value
      }
    }

    return res
  }
}