How to transpose an array more Swiftly?

后端 未结 2 1834
被撕碎了的回忆
被撕碎了的回忆 2020-12-19 11:35

I asked a similar question a while ago. It was asking how can I turn an array like this:

[[1,2,3],[4,5,6],[7,8,9]]

to this:



        
2条回答
  •  青春惊慌失措
    2020-12-19 12:16

    Here's an improvement on Shadow Of's answer:

    extension Collection where Self.Iterator.Element: RandomAccessCollection {
        // PRECONDITION: `self` must be rectangular, i.e. every row has equal size.
        func transposed() -> [[Self.Iterator.Element.Iterator.Element]] {
            guard let firstRow = self.first else { return [] }
            return firstRow.indices.map { index in
                self.map{ $0[index] }
            }
        }
    }
    
    let matrix = [
        [1, 2, 3, 4],
        [5, 6, 7, 8],
        [9, 10, 11, 12],
    ]
    matrix.transposed().forEach{ print($0) }
    

提交回复
热议问题