假设我有一组核心数据对象。
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,现在我的数组中的对象具有以下indexValues
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中实现这一目标。
答案 0 :(得分:0)
简单的解决方案,使用此函数并传递有序 - 缺少索引 - 数组。
您必须将MyObject
替换为包含indexValue
属性的实际自定义类型,并添加代码以保存托管对象上下文。
func reindex(items : [MyObject])
{
for (index, item) in items.enumerated() {
item.indexValue = Int64(index + 1)
}
// save the context
}