MayNotBe
MayNotBe

Reputation: 2140

Swift 2D array of String

I want to create an array that holds two String arrays for a picker. Each array needs to be 1 - 30 (Strings, not Ints)

I think I'm doing this right but Xcode disagrees:

var scorePickerArray: [[String]] = []

    for var i: Int = 0; i < 2; i++
        {
            for var j: Int = 0; j < 30; j++
            {
                scorePickerArray[i][j] = String(j + 1)
            }
        }

I'm getting an "array index out of bounds" for scorePickerArray[0][0]

What am I doing wrong? (probably something very obvious)

Upvotes: 1

Views: 3653

Answers (1)

Eric Aya
Eric Aya

Reputation: 70098

Your version didn't work because when you ask for scorePickerArray[0][0], the second dimension is not yet created, so it's "out of bounds", that is to say scorePickerArray[0] does not have members yet and you can't access them with subscript ([0][0]).

Solution:

var scorePickerArray = [[String]]()

var temp = [String]()

for i in 1...30 {
    temp.append("\(i)")
}

for i in 0...1 {
    scorePickerArray.append(temp)
}

Result:

[["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30"], ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30"]]


Update for Swift 2

A better solution for Swift 2 would be to use an array of Ints generated from a range (with each Int mapped to String) instead of loops:

let innerArray = Array(1...30).map { String($0) }

Then to repeat it like this:

let scorePickerArray = Array(count:2, repeatedValue: innerArray)

Upvotes: 3

Related Questions