Это работало в Swift 4.
extension Array where Element: Collection {
public func transposed() -> [[Element.Iterator.Element]] {
var result : [[Element.Iterator.Element]] = [[]]
for row in self {
for (y,column) in row.enumerated() {
while (result.count <= y) {
result.append([])
}
result[y].append(column)
}
}
return result
}
}
Затем также прошло модульное тестирование:
func testTransposed() {
XCTAssertEqual([[1]].transposed(), [[1]])
XCTAssertEqual([[1,2,3],[4,5]].transposed(), [[1,4],[2,5],[3]])
XCTAssertEqual([[4,1],[5,2],[3]].transposed(),[[4,5,3],[1,2]])
XCTAssertEqual([[1,2,3]].transposed(), [[1],[2],[3]])
XCTAssertEqual([[1],[2],[3]].transposed(),[[1,2,3]])
}