如何从嵌套在Sequence中的类型定义输出类型

时间:2018-08-03 14:09:52

标签: swift

我想扩展目录。我的结构是:

var points:[String:Set<Double>] = ["x":[0.0, 2.0, 4.0, 6.0],
                                   "y":[10.0, 20.0, 30.0],
                                   z":[100.0, 200.0]]

我需要将"x""y""z" ....的所有组合作为一组平面字典:

[["x":0.0, "y":10.0, "z":100.0],
 ["x":0.0, "y":10.0, "z":200.0],
 ["x":0.0, "y":20.0, "z":100.0],
 ["x":0.0, "y":20.0, "z":200.0],
 ["x":0.0, "y":30.0, "z":100.0],
 ["x":0.0, "y":30.0, "z":200.0],
 ["x":2.0, "y":10.0, "z":100.0],
 ["x":2.0, "y":10.0, "z":200.0],
 ["x":2.0, "y":20.0, "z":100.0],
 ["x":2.0, "y":20.0, "z":200.0],
 ["x":2.0, "y":30.0, "z":100.0],
 ["x":2.0, "y":30.0, "z":200.0],
 ....]

因此在这种特殊情况下,扩展标头将如下所示:

 extension Dictionary where Value == Set<Double> {

      var explode:[[String:Double]] {
          ....
      }
 }

但是,如果我想使其更通用?如何声明类型?

 extension Dictionary where Value:Sequence {

      var explode:[[String:Sequence.Element]] {
          ....
      }
 }

它不起作用:Associated type 'Element' can only be used with a concrete type or generic parameter base。我能理解但是如何获取Element类型并使用其id输出定义呢?

1 个答案:

答案 0 :(得分:2)

您非常亲密。您需要引用R = {(a,1), (b,2)}(具体类型参数),而不是R(协议)。

Value

也就是说,我很惊讶您的返回值可能涉及Sequence。我希望它的密码与您的字典相同。

extension Dictionary where Value: Sequence {

    var explode:[[String:Value.Element]] {
        ...
    }
}