Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement delete and move function using SwiftUI framework

Tags:

swiftui

Not able to delete and move row at for the item in the list view.

Apple provided in their training video these methods but its not working

For removing:

array.remove(atOffsets: IndexSet)

For moving:

array.move(fromOffsets: IndexSet, toOffset: Int)

Both of these method are not available in the apple documentation.

Simulator Screen

like image 757
Ashim Dahal Avatar asked Jan 01 '23 22:01

Ashim Dahal


1 Answers

These methods are part of the Swift 5.1 standard library, which Apple will make available with a future beta of Xcode. In the meantime, you can use these extensions:

extension Array {
    mutating func remove(atOffsets offsets: IndexSet) {
        let suffixStart = halfStablePartition { index, _ in
            return offsets.contains(index)
        }
        removeSubrange(suffixStart...)
    }

    mutating func move(fromOffsets source: IndexSet, toOffset destination: Int) {
        let suffixStart = halfStablePartition { index, _ in
            return source.contains(index)
        }
        let suffix = self[suffixStart...]
        removeSubrange(suffixStart...)
        insert(contentsOf: suffix, at: destination)
    }

    mutating func halfStablePartition(isSuffixElement predicate: (Index, Element) -> Bool) -> Index {
        guard var i = firstIndex(where: predicate) else {
            return endIndex
        }

        var j = index(after: i)
        while j != endIndex {
            if !predicate(j, self[j]) {
                swapAt(i, j)
                formIndex(after: &i)
            }
            formIndex(after: &j)
        }
        return i
    }

    func firstIndex(where predicate: (Index, Element) -> Bool) -> Index? {
        for (index, element) in self.enumerated() {
            if predicate(index, element) {
                return index
            }
        }
        return nil
    }
}
like image 163
Patrick Gili Avatar answered Jan 03 '23 12:01

Patrick Gili