Honey Honey - 6 months ago 17
Swift Question

Multiple errors with using multidimensional array of generics

I am trying to rotate a 2 dimensional array of any Type. I am using generics so that I could Strings & Ints or any other type.

import UIKit

let someArray = [[1,2,3],[7,8,9],[11,93,87]]

print(someArray[0])


func rotateArray<T> (array:[[T]]) ->Array{
var tempArray = [[T]]()

for i in 0..<array.count{

for j in 0..<array.count{

tempArray[j][array.count-i-1] = array[i][j]
}

}
return tempArray

}

someArray.count

let x = rotateArray(someArray)


However I get the following errors ( There could be other errors that I am not aware of), I also read this question and some others but couldn't relate to it.


  • reference to generic type 'Array' requires arguments in <..>

  • Binary Operator '..<' Cannot be applied to two 'Int' operands

  • Edit after fixing the initial two errors:
    fatal error: Index out of range



What are the things that I am doing wrong? Kindly include details, I am a complete noob.

Rob Rob
Answer

In addition to making your method return type [[T]], you have other problems here. You are instantiating tempArray (the array that will hold the arrays inside), but you are not instantiating those inner arrays. And you can't just use subscript operator, but rather you have to append to your respective arrays.

For example, if you want to rotate clockwise 90 degrees, it would be:

func rotateArray<T> (array:[[T]]) -> [[T]] {
    var tempArray = [[T]]()

    for j in 0 ..< array.first!.count {
        tempArray.append([T]())
        for i in (array.count-1).stride(through: 0, by: -1) {
            tempArray[j].append(array[i][j])
        }
    }
    return tempArray
}

Thus

[[1, 2, 3],
[7, 8, 9],
[11, 93, 87]]

Becomes

[[11, 7, 1],
[93, 8, 2],
[87, 9, 3]]