how to access elements in a 2D Array in Swift

若如初见. 提交于 2021-02-18 19:32:41

问题


I am trying to read string variables from a single array (or more precisely from an array of arrays of strings, as clarified in the accepted answer) in Swift. The following reads the entire array.

    var array = [["W", "X", "Y", "Z"], ["A", "B", "C", "D"]]
    print(array[0],array[1])

How do I read a pair of variables, e.g. "X" and "D" ?


回答1:


array is an array of arrays of strings. Or, type Array<Array<String>>. array[0] will return the first element of the array, which is an array of strings, or Array<String>. Which means you must then access another single element of that array. Step by step, the code would look like this:

let array = [["W", "X", "Y", "Z"], ["A", "B", "C", "D"]]

let firstArray = array[0]  // ["W", "X", "Y", "Z"]
let X = firstArray[1]  // "X"

let secondArray = array[1]  // ["A", "B", "C", "D"]
let D = secondArray[3]  // "D" 

The short version looks like this:

print(array[0][1], array[1][3])  // "X D"



回答2:


Just provide an index of the first level, and then the second level.

print(array[1][3])

You can also iterate over arrays of multiple levels in this way

for subarray of array {
    for element of subarray {
        print(element)
    }
}



回答3:


You could zip an array of indices (one for each inner array) with the arrays of arrays (array), and use a map call on this zipped sequence to construct an array with one elements from each inner array. E.g.

let array = [["W", "X", "Y", "Z"], ["A", "B", "C", "D"]]
let innerIdxs = [1, 3]

let innerElements = zip(array, innerIdxs).map { $0[$1] }
print(innerElements) // ["X", "D"]

Just note that this will lead to a runtime exception due to index out of bounds in case any of the indices in the innerIdxs array exceed the number of elements - 1 (in the corresponding inner array). A safer approach would be validating the index prior to using it, e.g.:

let innerElements = zip(array, innerIdxs)
    .map { 0..<$0.count ~= $1 ? $0[$1] : "invalid index" }

which would yield the following innerElements given the following few examples of innerIdxs arrays:

let innerIdxs = [4, 3] 
    // ... -> innerElements = ["invalid index", "D"]

let innerIdxs = [2, -1] 
    // ... -> innerElements = ["Y", "invalid index"]



回答4:


array[0][0] // "W"
array[0][1] // "X"
array[0][2] // "Y"
array[1][0] // "A"

I guess you now get it! ;)

PS: With a nested for you can have:

for i in 0...3 {
    for j in 0...3 {
        print(array[i][j])
    }
}


来源:https://stackoverflow.com/questions/41600670/how-to-access-elements-in-a-2d-array-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!