0

I have a foreach statement that I'd like to use a variable in place of index for example.

Right now this works fine.

ForEach(vm.trainingdata) { index in
Text(index.foo1.data)
}

What I would like to do is this, but because index... is stored as a string I'm just getting back a string (which is expected I know).

ForEach(vm.trainingdata) { index in

fooArray = ["index.foo1.data", "index.foo2.data"]
Text(fooArray[2])
}
2
  • 3
    I'm confused what the question is here. Can you be a bit more descriptive? Maybe input vs expected output? Commented Sep 1, 2021 at 2:05
  • 1
    I don’t understand where fooArray comes from in your second code snippet. Commented Sep 1, 2021 at 14:55

2 Answers 2

2

Here's from an article I found:

There several ways to loop through an array in Swift, but using the enumerated() method is one of my favorites because it iterates over each of the items while also telling you the items's position in the array.

let array = ["Apples", "Peaches", "Plums"]

for (index, item) in array.enumerated() {
    print("Found \(item) at position \(index)")
}
Sign up to request clarification or add additional context in comments.

Comments

0

try this:

fooArray = ["index.foo1.data", "index.foo2.data"]

ForEach(vm.trainingdata.indices) { index in
    Text(vm.trainingdata[index])
    Text(fooArray[index])
}

of course you need to make sure fooArray has the same size as vm.trainingdata

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.