如何在Swift中将多个数组合并为具有数组值的一个数组?

时间:2018-09-23 08:54:51

标签: ios arrays swift

如何在Swift中将多个数组合并为具有数组值的一个数组?

var arr1 = ["1", "2", "3"]
var arr2 = ["a", "b", "c"]
var arr3 = ["aa", "bb", "cc"]

  [["1", "a", "aa"], ["2", "b", "bb"], ["1", "c", "cc"]]

2 个答案:

答案 0 :(得分:1)

我认为您想要的是将三个数组合并为2D数组,然后对其进行转置。

要转置2D数组,您可以在此question中找到许多解决方案。

这在注释中使用了Crashalot的解决方案:

fileprivate func transpose<T>(input: [[T]]) -> [[T]] {
    if input.isEmpty { return [[T]]() }
    let count = input[0].count
    var out = [[T]](repeating: [T](), count: count)
    for outer in input {
        for (index, inner) in outer.enumerated() {
            out[index].append(inner)
        }
    }
    return out

}

var arr1 = ["1", "2", "3"]
var arr2 = ["a", "b", "c"]
var arr3 = ["aa", "bb", "cc"]

transpose(input: [arr1, arr2, arr3])

如果您想更快捷地transpose,可以使用此方法(从here修改):

extension Collection where Self.Element: RandomAccessCollection {
    func transposed() -> [[Self.Iterator.Element.Iterator.Element]]? {
        guard Set(self.map { $0.count }).count == 1 else { return nil }

        guard let firstRow = self.first else { return [] }
        return firstRow.indices.map { index in
            self.map{ $0[index] }
        }
    }
}

答案 1 :(得分:0)

如果您愿意,这是一种幼稚的表达方式。

[arr1,arr2,arr3].reduce([[],[],[]]) { result, next -> [[String]] in
   return (0..<(next.count)).map{
         var array = Array.init(result[$0])
         array.append(next[$0]);
         return array
   }
}

或更直接地:

[arr1,arr2,arr3].reduce(into: [[],[],[]]) { ( result : inout [[String]], next) in
 _ = (0..<(next.count)).map{ result[$0].append(next[$0]);}
 }