2

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.

1 Answer 1

2

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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Your answer seems better approach of my way, I am doing 2 times Complexity: O(n), but you are doing 1 time Complexity: O(1) and 1 time Complexity: O(n). thanks

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.