colindunn
colindunn

Reputation: 3163

iOS Swift: Sort array into three dimensional array

I have an array of CKRecords that I would like to sort into a three dimensional array. Within the first array is an array of dates, and each date is an array of names, where a name is an Int between 0 and 4. I'm successfully sorting my records into a two dimensional array currently (code below).

Name can be retrieved with record.objectForKey("Name") as Int

func buildIndex(records: [CKRecord]) -> [[CKRecord]] {
    var dates = [NSDate]()
    var result = [[[CKRecord]]]()

    for record in records {
        var date = record.objectForKey("startTime") as NSDate

        if !contains(dates, date) {
            dates.append(date)
        }
    }

    for date in dates {
        var recordForDate = [CKRecord]()

        for (index, exercise) in enumerate(records) {
            let created = exercise.objectForKey("startTime") as NSDate

            if date == created {
                let record = records[index] as CKRecord
                recordForDate.append(record)
            }
        }
        result.append(recordForDate)
    }

    return result
}

Not sure the best way to approach this problem. Even general guidance would be appreciated.

Upvotes: 0

Views: 235

Answers (1)

lindon fox
lindon fox

Reputation: 3318

General Overview:

Step 1 - choose your sort algorithm. I find that the insertion sort algorithm is the easiest for me to understand and is fast too.

Step 2 - decide on your data structure. You could use a 2-dimensional array. The first dimension represents your dates, and the second dimension represents your records. So the array might be defined like this List<List<CKRecord>>. So the first entry would contain a list (List<CKRecord>) of all the records with the earliest date (it may be one or many).

Basic Steps

(with a 2-D array)

  1. So start with the empty data structure
  2. Figure out which Date list it should go into
  3. If the date does not exist yet, you need to sort the date into the correct position and add a new array/list with the new entry as the only contents
  4. If the date already exists, you need to sort the record into the correct position of the already existing list of records
  5. Enjoy

Upvotes: 1

Related Questions