arrays - 如何在 Swift 3 中重新排序核心数据对象数组并重新排序其 Int 属性

标签 arrays swift sorting core-data swift3

假设我有一个 Core Data 对象数组。

let array = [Object1, Object2, Object3, Object4, Object5, Object6, Object7]

每个对象都有一个名为 indexValue : Int64 的属性

首先,这些对象具有以下 indexValue 属性值:

Object1 has indexValue = 1
Object2 has indexValue = 2
Object3 has indexValue = 3
Object4 has indexValue = 4
Object5 has indexValue = 5
Object6 has indexValue = 6
Object7 has indexValue = 7

现在假设我删除了 Object3 和 Object6,现在数组中的对象具有以下索引值

Object1 has indexValue = 1
Object2 has indexValue = 2
Object4 has indexValue = 4
Object5 has indexValue = 5
Object7 has indexValue = 7

删除后,我想按以下方式重新排序该数组: 我想将此数组的 indexValue 属性更改为以下状态:

Object1 has indexValue = 1
Object2 has indexValue = 2
Object4 has indexValue = 3
Object5 has indexValue = 4
Object7 has indexValue = 5

主要的困难是在给出新的indexValue值的同时保持旧的顺序。我正在寻找一种算法来在 Swift 3 中完成此任务。

最佳答案

简单的解决方案,使用此函数并传递缺少索引的有序数组。

您必须将 MyObject 替换为包含 indexValue 属性的实际自定义类型,并添加代码以保存托管对象上下文。

func reindex(items : [MyObject])
{
    for (index, item) in items.enumerated() {
        item.indexValue = Int64(index + 1)
    }
    // save the context
}

关于arrays - 如何在 Swift 3 中重新排序核心数据对象数组并重新排序其 Int 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45458713/

相关文章:

python - n维数组中唯一值的索引

php - 将以下查询显示为逗号分隔列表

swift - Swift 4 中无法对结构体数组进行计数或迭代

javascript - 按字母顺序对字符串数组进行排序,然后按数字顺序按特殊字符排序

android - 如何按 firebase 中的子键值排序?

java - 使数组的值成为数字列表?

arrays - 数组从 a1,..,an,b1,..,bn 移动到 a1,b1,..,an,bn

ios - 由于未捕获的异常 'RLMException' 而终止应用程序,原因 : 'This method may only be called on RLMArray instances retrieved from an RLMRealm

ios - 我什么时候想在 swift 2.2 中使用 static, final, private?

c# - Entity Framework : OrderBy() numeric property when mapped column type is textual