periphery icon indicating copy to clipboard operation
periphery copied to clipboard

Wondering if I'm doing something wrong but the index is clearly being written to; Rename things to make generic.

Open Aayush9029 opened this issue 6 months ago • 0 comments

~/Desktop/xxxx/xxxx/xxx/xxxxx.swift:14:9: warning: Property 'index' is assigned, but never used

import Models
import SwiftUI

struct Item: Identifiable, Equatable {
    let id: UUID
    var data: SmolItem
    var index: Int
    
    static func == (lhs: Item, rhs: Item) -> Bool {
        lhs.id == rhs.id
    }
}

@Observable
class MyViewModel {
    var items: [Item] = []
    
    init(smolItems: [SmolItem]) {
        self.items = smolItems.enumerated().map { index, data in
            Item(id: UUID(), data: data, index: index)
        }
    }
    
    func moveUp(item: Item) {
        move(item: item, by: -1)
    }
    
    func moveDown(item: Item) {
        move(item: item, by: 1)
    }
    
    private func move(item: Item, by offset: Int) {
        guard let index = items.firstIndex(where: { $0 == item }),
              items.indices.contains(index + offset) else { return }
        
        items.swapAt(index, index + offset)
        updateIndices()
    }
    
    private func updateIndices() {
        for index in items.indices {
            items[index].index = index
        }
    }
}

Aayush9029 avatar Aug 18 '24 15:08 Aayush9029