Multidimensional arrays in Swift

后端 未结 7 969
离开以前
离开以前 2020-11-30 22:43

Edit: As Adam Washington points out, as from Beta 6, this code works as is, so the question is no longer relevant.

I am trying to create and iterate through a two d

7条回答
  •  再見小時候
    2020-11-30 22:48

    Using http://blog.trolieb.com/trouble-multidimensional-arrays-swift/ as a start, I added generics to mine:

    class Array2DTyped{
    
    var cols:Int, rows:Int
    var matrix:[T]
    
    init(cols:Int, rows:Int, defaultValue:T){
        self.cols = cols
        self.rows = rows
        matrix = Array(count:cols*rows,repeatedValue:defaultValue)
    }
    
    subscript(col:Int, row:Int) -> T {
        get{
            return matrix[cols * row + col]
        }
        set{
            matrix[cols * row + col] = newValue
        }
    }
    
    func colCount() -> Int {
        return self.cols
    }
    
    func rowCount() -> Int {
        return self.rows
    }
    }
    

提交回复
热议问题