Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I animated index of an array when using an id in ForEach in SwiftUI

I want animate my ForEach view depending the index of array, here is my code:

struct ContentView: View {
    
    @State private var array: [MyType] = [MyType("A"), MyType("B"), MyType("C"), MyType("D")]
    
    var body: some View {
        
        VStack(spacing: 10.0) {
            
            ForEach(array, id:\.id) { item in
                Text(item.string)
                    .frame(width: 25, height: 25)
                    .background(Color.gray.opacity(0.5).cornerRadius(5.0))
            }
            .animation(.default, value: array)

            Button("Move to down") {
                
                array.indices.forEach { index in
                    
                    if ((array[index].index + 1) < array.count) { array[index].index += 1 }
                    else { array[index].index = 0 }
                    
                }
                
                array.sort(by: { (lhs, rhs) in return (lhs.index < rhs.index) })
                
            }
 
        }
        .fixedSize()
        .padding()

    }

}


struct MyType: Equatable {
    
    private static var nextIndexValue: Int = 0
    
    let id: UUID = UUID()
    var index: Int
    var string: String
    
    init(_ string: String) {
        self.index = MyType.nextIndexValue
        self.string = string
        MyType.nextIndexValue += 1
    }
    
}

This approach seems works fine when I am facing with a small size array, my issue with this approach is that I have to apply my updating index logic once and then sorting the array right after it. Which I believe it is far away to be a good approach. I was wondering if there is a simpler way or approach that could be better approach with large arrays. The goal of this question is searching for an approach that is better in performance.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Not really sure what do you mean, but next does the same in much simpler way and does not depend on indices at all:

Button("Move to down") {
    let last = array.removeLast()
    array.insert(last, at: 0)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading