Reputation: 36287
I have done this in Objective-C but I can't do what I want to do in Swift.
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
fatal error: Index out of range
What are the things that I am doing wrong? Kindly include details, I am a complete noob.
Upvotes: 1
Views: 135
Reputation: 437582
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 column in 0 ..< array.first!.count {
var rowArray = [T]()
for row in (0 ..< array.count).reverse() {
rowArray.append(array[row][column])
}
tempArray.append(rowArray)
}
return tempArray
}
Thus
[[1, 2, 3],
[7, 8, 9],
[11, 93, 87]]
Becomes
[[11, 7, 1],
[93, 8, 2],
[87, 9, 3]]
Upvotes: 1
Reputation: 118681
You have written the return type -> Array
, but since Array is generic, you need to specify what it contains, such as Array<Something>
or equivalently [Something]
.
Seemingly, you want to return the same "shape"/type of array as the input, so you can use -> [[T]]
for your return type.
(I'm not sure why the compiler produced an error about ..<
, but it goes away if you fix the first issue.)
Upvotes: 2