Is there a way to declare an arbitrary number of arrays in Swift?

Viewed 79

I'm new to programming and to Swift; apologies if I'm asking an obvious question. I'm trying to simulate a ranked-choice voting algorithm. Several parts of it work, but I'm stuck on a basic idea: I need to generate an arbitrary number of arrays that contain each voter's imaginary votes. I want software to produce many arrays that look more or less like this:

var ballot1 = ["candidateB", "candidateA", "candidateD"]
var ballot2 = ["candidateC", "candidateD"]

To this point, I have hand-written the ones I need, but I want to automate the process. Is there a way, in Swift, that I can declare an arbitrary number of those variables-containing-arrays without hand-writing each one? I'd like to be able to specify an arbitrary integer - 10, say...or 2,500? - and let a function spit out that many arrays. (I've separately developed a function to create one array of random-within-parameters length containing random-within-parameters contents, but I'm stuck trying to replicate that function across many arrays.)

I've tried various kinds of for—in loops, but I run into various errors whenever I try to use code to declare the new variable. Is there a simple way to get software to declare variables with names that increment (e.g., ballot1, ballot2, ballot3, etc.)? Am I missing something obvious? Thanks for any advice.

1 Answers

Use an array of arrays, as jnpdx says in their comment.

let ballot1 = ["candidateB", "candidateA", "candidateD"] 
let ballot2 = ["candidateC", "candidateD"]
let ballots = [ballot1, ballot2]

or just

let ballots = [["candidateB", "candidateA", "candidateD"],
    ["candidateC", "candidateD"]]

Then you can refer to your ballots using indexes:

ballots[0] would give you an array of candidates for the first ballot, or you could loop through the outer array:

for (index, ballot) in ballots.enumerated() {
   print("Ballot \(index+1) has candidates \(ballot[index])")
}

Note that you might want to make each ballot a struct, with fields for a title, the array of candidates, and any other information you might want. Then you could have an array of ballot structs:

struct Ballot {
   let title: String
   let description: String? // Optional field
   let candidates: [String]
}

And then:

let ballots = [Ballot(title: "5th congressional district",
                  description: nil,
                  candidates: ["Joe", "Briana", "Jamal", "Ivan"]),
               Ballot(title: "Mayor",
                  description: nil,
                  candidates: ["Adrienne", "Moisha", "Dave", "Demtri"])
              ]

And:

for aBallot in ballots {
    print("Ballot titled \(aBallot.title) has candidates \(aBallot.candidates)")
Related