development

Swift의 2 차원 배열

big-blog 2020. 9. 6. 11:34
반응형

Swift의 2 차원 배열


Swift의 2D 배열에 대해 너무 혼란 스러워요. 단계별로 설명하겠습니다. 그리고 제가 틀렸다면 제발 정정 해 주시겠습니까?

가장 먼저; 빈 배열 선언 :

class test{
    var my2Darr = Int[][]()
}

두 번째로 배열을 채 웁니다. (예를 들어 my2Darr[i][j] = 0i, j는 for 루프 변수)

class test {
    var my2Darr = Int[][]()
    init() {
        for(var i:Int=0;i<10;i++) {
            for(var j:Int=0;j<10;j++) {
                my2Darr[i][j]=18   /*  Is this correct?  */
            }
        }
    }
}

그리고 마지막으로 배열의 요소 편집

class test {
    var my2Darr = Int[][]()
    init() {
        ....  //same as up code
    }
    func edit(number:Int,index:Int){
        my2Darr[index][index] = number
        // Is this correct? and What if index is bigger
        // than i or j... Can we control that like 
        if (my2Darr[i][j] == nil) { ...  }   */
    }
}

가변 배열 정의

// 2 dimensional array of arrays of Ints 
var arr = [[Int]]() 

또는:

// 2 dimensional array of arrays of Ints 
var arr: [[Int]] = [] 

또는 미리 정의 된 크기의 배열이 필요한 경우 (주석에서 @ 0x7fffffff에 언급 됨) :

// 2 dimensional array of arrays of Ints set to 0. Arrays size is 10x5
var arr = Array(count: 3, repeatedValue: Array(count: 2, repeatedValue: 0))

// ...and for Swift 3+:
var arr = Array(repeating: Array(repeating: 0, count: 2), count: 3)

위치에서 요소 변경

arr[0][1] = 18

또는

let myVar = 18
arr[0][1] = myVar

하위 배열 변경

arr[1] = [123, 456, 789] 

또는

arr[0] += 234

또는

arr[0] += [345, 678]

이러한 변경 이전에 0 (영)의 3x2 배열이 있었다면 이제 다음과 같이됩니다.

[
  [0, 0, 234, 345, 678], // 5 elements!
  [123, 456, 789],
  [0, 0]
]

따라서 하위 배열은 변경 가능하며 행렬을 나타내는 초기 배열을 재정의 할 수 있습니다.

액세스하기 전에 크기 / 경계를 검토하십시오.

let a = 0
let b = 1

if arr.count > a && arr[a].count > b {
    println(arr[a][b])
}

설명 : 3 차원 및 N 차원 배열에 대해 동일한 태그 규칙.


문서에서 :

You can create multidimensional arrays by nesting pairs of square brackets, where the name of the base type of the elements is contained in the innermost pair of square brackets. For example, you can create a three-dimensional array of integers using three sets of square brackets:

var array3D: [[[Int]]] = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]

When accessing the elements in a multidimensional array, the left-most subscript index refers to the element at that index in the outermost array. The next subscript index to the right refers to the element at that index in the array that’s nested one level in. And so on. This means that in the example above, array3D[0] refers to [[1, 2], [3, 4]], array3D[0][1] refers to [3, 4], and array3D[0][1][1] refers to the value 4.


You should be careful when you're using Array(repeating: Array(repeating: {value}, count: 80), count: 24).

If the value is an object, which is initialized by MyClass(), then they will use the same reference.

Array(repeating: Array(repeating: MyClass(), count: 80), count: 24) doesn't create a new instance of MyClass in each array element. This method only creates MyClass once and puts it into the array.

Here's a safe way to initialize a multidimensional array.

private var matrix: [[MyClass]] = MyClass.newMatrix()

private static func newMatrix() -> [[MyClass]] {
    var matrix: [[MyClass]] = []

    for i in 0...23 {
        matrix.append( [] )

        for _ in 0...79 {
            matrix[i].append( MyClass() )
        }
    }

    return matrix
}

In Swift 4

var arr = Array(repeating: Array(repeating: 0, count: 2), count: 3)
// [[0, 0], [0, 0], [0, 0]]

According to Apple documents for swift 4.1 you can use this struct so easily to create a 2D array:

Link: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Subscripts.html

Code sample:

struct Matrix {
let rows: Int, columns: Int
var grid: [Double]
init(rows: Int, columns: Int) {
    self.rows = rows
    self.columns = columns
    grid = Array(repeating: 0.0, count: rows * columns)
}
func indexIsValid(row: Int, column: Int) -> Bool {
    return row >= 0 && row < rows && column >= 0 && column < columns
}
subscript(row: Int, column: Int) -> Double {
    get {
        assert(indexIsValid(row: row, column: column), "Index out of range")
        return grid[(row * columns) + column]
    }
    set {
        assert(indexIsValid(row: row, column: column), "Index out of range")
        grid[(row * columns) + column] = newValue
    }
}

}


Make it Generic Swift 4

struct Matrix<T> {
    let rows: Int, columns: Int
    var grid: [T]
    init(rows: Int, columns: Int,defaultValue: T) {
        self.rows = rows
        self.columns = columns
        grid = Array(repeating: defaultValue, count: rows * columns) as! [T]
    }
    func indexIsValid(row: Int, column: Int) -> Bool {
        return row >= 0 && row < rows && column >= 0 && column < columns
    }
    subscript(row: Int, column: Int) -> T {
        get {
            assert(indexIsValid(row: row, column: column), "Index out of range")
            return grid[(row * columns) + column]
        }
        set {
            assert(indexIsValid(row: row, column: column), "Index out of range")
            grid[(row * columns) + column] = newValue
        }
    }
}


var matrix:Matrix<Bool> = Matrix(rows: 1000, columns: 1000,defaultValue:false)

matrix[0,10] = true


print(matrix[0,10])

참고URL : https://stackoverflow.com/questions/25127700/two-dimensional-array-in-swift

반응형