2017-08-02 17 views
0

私はコアデータオブジェクトの配列を持っているとしましょう。コアデータオブジェクトの配列を並べ替え、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 

が今度は言わせて、私は、例えばオブジェクト3と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でこれを達成するためのアルゴリズムを探しています。

+1

したがって、配列内の各オブジェクトの実際のインデックスの値をindexValueに設定しますか? – nbloqs

+0

@nbloqs 'i ++'はSwift 3では動作せず、 'indexValue'は' Int64'と1ベースです。 – vadian

答えて

0

単純な解法では、この関数を使用して、配列の欠落しているインデックス配列を渡します。

indexValue属性を含む実際のカスタムタイプにMyObjectを置き換え、管理対象オブジェクトコンテキストを保存するコードを追加する必要があります。

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

ありがとう、それはまさに私が探していたものでした! – Adelmaer

関連する問題