swiftui onDelete不适用于sortedData

时间:2019-11-18 16:49:58

标签: ios swiftui

我有一个显示为列表的数组,onDelete按钮按预期方式工作,func如下所示:

from pyspark import SparkContext
from pyspark import SparkFiles
import urllib

sc = SparkContext()
ftp_path = "ftp://Username:password@ftplocation.com/path_to_file"
file_path_clean = urllib.parse.urlencode(ftp_path, safe='|')
print(f"file_path_clean: {file_path_clean}")
sc.addFile(ftp_path)
filename = SparkFiles.get(file_path.split('/')[-1])
print(f"filename: {filename}")

rdd = sc.textFile("file://" + filename)
print("We got past rdd = sc.textFile(file:// + filename)")
rdd.take(10)
rdd.collect()
print(rdd)

但是如果我对数组进行排序,则此函数会删除错误的条目

我这样排序:

func removeGames(at offsets: IndexSet) {
        listGames.games.remove(atOffsets: offsets)
    }

任何人都知道,如何使onDelete正常工作?

1 个答案:

答案 0 :(得分:0)

只需将remove应用于已排序列表,它将按预期工作:

func removeGames(at offsets: IndexSet) {
    listGames.games.sorted(by: {$0.self.dateOfGame>$1.self.dateOfGame}).remove(atOffsets: offsets)
}

编辑

另一种方法是将一组索引(在排序数组中)映射到另一组(在未排序数组中)。在伪代码中,您可以这样开始:

let itemToRemove = sortedArray[sortedIndex]
let unsortedIndex = unsortedArray.firstIndex(of: itemToRemove)

您可以将此逻辑应用于整个IndexSet:

let unsortedIdices = sortedIndices.compactMap { unsortedArray.firstIndex(of: sortedArray[$0]) }

这将为您提供一个数组,您可以将其转换为IndexSet

let unsortedIdices = IndexSet(sortedIndices.compactMap { unsortedArray.firstIndex(of: sortedArray[$0]) })

在您的特定示例中如下所示:

 func removeGames(at sortedOffsets: IndexSet) {
     let unsoretdOffsets = IndexSet(sortedOffsets.compactMap { listGames.games.firstIndex(of: listGames.games.sorted(by: {$0.self.dateOfGame>$1.self.dateOfGame})[$0] ) })
     listGames.games.remove(atOffsets: unsoretdOffsets)
}