moosgrn
moosgrn

Reputation: 379

Simplest Way to Iterate Through Multiple Arrays of Structs?

Looking to increment through multiple arrays of structs using one of their variables for number of loops per. Thanks!

struct Example {
    var partOne: Int
    var partTwo: Int
    var partThree: Int
}

var one = Example(partOne: 10, partTwo: 11, partThree: 12)
var two = Example(partOne: 10, partTwo: 11, partThree: 12)

var arrayOfExamples = [one, two]

for i in 0...arrayOfExamples[0].partThree {
    print(i)
}

//once i = 12, then

for i in 0...arrayOfExamples[1].partThree {
    print(i)
}

Upvotes: 0

Views: 133

Answers (1)

vacawama
vacawama

Reputation: 154603

Just use nested loops with the outer loop iterating over the items of the arrayOfExamples:

for item in arrayOfExamples {
    for i in 0...item.partThree {
        print(i)
    }
}

By using KeyPaths, you can write a function that iterates over the values with the property specified by the caller:

func iterateOverKeyPath(array: [Example], keyPath: KeyPath<Example, Int>) {
    for item in array {
        for i in 0...item[keyPath: keyPath] {
            print(i)
        }
    }
}

// iterate using partThree property
iterateOverKeyPath(array: arrayOfExamples, keyPath: \Example.partThree)

// now do the same for partTwo
iterateOverKeyPath(array: arrayOfExamples, keyPath: \Example.partTwo)

And there's nothing really special about the Example struct, so we could make this generic to work for any type:

func iterateOverKeyPath<T>(array: [T], keyPath: KeyPath<T, Int>) {
    for item in array {
        for i in 0...item[keyPath: keyPath] {
            print(i)
        }
    }
}

Upvotes: 1

Related Questions