字典的快速组合

时间:2017-11-12 05:44:44

标签: swift dictionary combinations

在我使用此版本的func组合之前:

func combinationsT<T>(of array: [[T]]) -> [[T]] {
    return array.reduce([[]]) {
        var x = [[T]]()
        for i in $0 {
            for j in $1 {
                x.append(i + [j])
            }
        }
        return x
    }
}

var p1 = [[1,2,3],[0,1]]
var c1 = combinationsT(of: p1)
print(c1) 

输出为[[1, 0], [1, 1], [2, 0], [2, 1], [3, 0], [3, 1]]

现在我想将其更改为使用Dictionary,但有一些问题:

func combinations(of parList: [String : [Any]]) -> [String : [Any]] {
    return parList.reduce([:]) {
        var x = [String : [Any]]()

        for i in $0 {
            for j in $1.value {
                //x.updateValue(i + [j], forKey: $1.key)
            }
        }

        return x
    }
}

var p2 = [String : [Any]]()
p2.updateValue([1,2,3], forKey: "period")
p2.updateValue([0,1], forKey: "type")
var c2 = combinations(of: p2)
print(c2)

输出应为[["period" : 1, "type" : 0], ..., ["period" : 3, "type" : 1]]

0 个答案:

没有答案