Swift 2D Array Generic Extension - problem with getting the second dimension

I am trying to convert the following function to a general extension for 2D arrays.

func rotate(_ input: [[Int]]) -> [[Int]]
{
  let length = input[0].count
  var value = Array(repeating: [Int](), count: length)
  for index in 0 ..< length
  {
    value[index] = input.map { $0[index] }.reversed()
  }
  return value
}

I am specifically obsessed with how to specify restrictions that allow me to access the second dimension. Here is a failed attempt:

extension Array where Element: Collection, Element.Iterator.Element: Collection
{
  private func rotate()
  {
    let count = self[0].count // Element.IndexDistance instead of Int

    // Expression type 'Array<Element>' is ambiguous without more context
    var returnValue = Array(repeating: Element, count: 11)
    for index in 0 ..< count // Element.IndexDistance instead of Int
    {
      returnValue[index] = self.map { $0[index] }.reversed()
    }
    return returnValue
  }
}
+2
source share
1 answer

The problem is that the compiler does not know that your extension is for 2D arrays - it just knows that it is for collection arrays. Therefore, the associated types IndexDistanceand Indexnot necessarily Int.

, , , Element IndexDistance Index Int. 0..<count, count Int (IndexDistance) - map(_:) Int ( Index).

( , Element Array, .)

, Element.Iterator.Element: Collection , (, , ).

, typealias " " 2D-, Swift , , 2D- .

:

extension Array where Element: Collection, Element.Index == Int, Element.IndexDistance == Int {

    private func rotate() -> [[Element.Iterator.Element]] {

        typealias InnerElement = Element.Iterator.Element

        // in the case of an empty array, simply return an empty array
        if self.isEmpty { return [] } 
        let length = self[0].count

        var returnValue = [[InnerElement]](repeating: [InnerElement](), count: length)
        for index in 0..<length {
            returnValue[index] = self.map{ $0[index] }.reversed()
        }
        return returnValue
    }
}

, @MartinR , , map(_:), typealias, "result":

private func rotate() -> [[Element.Iterator.Element]] {

    if self.isEmpty { return [] }
    let length = self[0].count

    return (0..<length).map { index in
        self.map { $0[index] }.reversed()
    }
}

, Int ( , 2D-). indices.

, , indices Element , Index ( Array, indices CountableRange<Int>):

extension Array where Element: Collection, Element.Indices.Iterator.Element == Element.Index {
    private func rotate() -> [[Element.Iterator.Element]] {

        if self.isEmpty { return [] }

        return self[0].indices.map { index in
            self.map { $0[index] }.reversed()
        }
    }
}
+3

Source: https://habr.com/ru/post/1654735/


All Articles