简体   繁体   中英

Multidimensional arrays in Swift - Style

There are several idioms for declaring multidimensional arrays in Swift. Consider the following:

var ia1 = Array<Array<Int>>()
var ia2: Int[][] = []
typealias IntArray = Array<Int>
var ia3 = IntArray[]()
var ia4 = Int[][]()

ia1 += [[1, 2, 3], [2, 3, 4]]
ia2 += [[1, 2, 3], [2, 3, 4]]
ia3 += [[1, 2, 3], [2, 3, 4]]
ia4 += [[1, 2, 3], [2, 3, 4]]

let test = (ia1 == ia2) // true
let test2 = (ia3 == ia4) //true
// etc...

Is there actually any difference between the declarations that may bite the developer? And if not, is there any good reason to use one other over the others?

T[] is just syntactic sugar for Array<T> — there's no difference in implementation. Which style you prefer is a question of opinion.

Note that depending on what you're trying to model, multidimensional arrays might not be what you're looking for. It might make more sense to use a single array internally, and expose a multidimensional subscript to users of your data structure:

class GameBoard {

    let width = 10
    let height = 10
    let board: [Int]

    init() {
        board = [Int](count: width * height, repeatedValue: 0)
    }

    subscript(i: Int, j: Int) -> Int {
        return board[i + j * width]
    }

}

let b = GameBoard()

b[0,0]
b[4,1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM