当数组是二维数组时,我想在Array类型上创建一个扩展方法,例如。 [[Int]]
,但类型应该是通用的。我正在尝试做这样的事情:
extension Array [where Element : ???] {
public func transposed() -> ??? {
// ...
}
}
答案 0 :(得分:0)
这适用于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]])
}
答案 1 :(得分:0)
你可以这样做:
extension Array
{
func transposed<T>() -> [[T]] where Element == Array<T>
{
return self[0].indices.map{ i in self.map{$0[i]} }
}
}
let a = [ [1,2,3],
[4,5,6],
[7,8,9] ]
for r in a.transposed() {print(r)}
// [1, 4, 7]
// [2, 5, 8]
// [3, 6, 9]
// note that the matrix cannot be sparse