0

How can I loop from last item to first in a SwiftUi view?

I've tried the following

let myarray = ["1", "2", "3", "4"]
ForEach(stride(from: myarray.count, to: 1, by: -1), id: \.self) { i in
    print(myarray[i])
}

//desired output: 4 3 2 1

Thanks!!

1
  • 1
    ForEach is a View, not a for loop Commented Nov 21, 2022 at 22:56

1 Answer 1

1

You can use reversed:

ForEach(myarray.reversed(), id: \.self) { item in
    Text("\(item)")
}

Note that I'm using Text, not print -- this is SwiftUI, so you should have View code inside a ForEach.

Also note that \.self is generally dangerous in ForEach, but I'm assuming this is just sample code. Generally, you want something truly uniquely Identifiable

Sign up to request clarification or add additional context in comments.

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.