2017-08-02 67 views
0

假设我有一个Core Data对象数组。如何重排核心数据对象数组并重新排列其在Swift 3中的Int属性

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中完成这项工作。

+1

所以,你希望indexValue获取数组中每个对象的真实索引值? – nbloqs

+0

@nbloqs'i ++'在Swift 3中不起作用,'indexValue'是'Int64'和基于1的。 – vadian

回答

0

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

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

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

非常感谢,那正是我一直在寻找的! – Adelmaer