0

I'm trying to sort this array of dictionaries by age. When I try to iterate through the array of friends (last for in loop) and insert at a specific index, I get a fatal error:

Array index is out of range when inserting an element.

let friends = [
    [
        "name" : "Alex",
        "age" : 23
    ],
    [
        "name" : "Massi",
        "age" : 38
    ],
    [
        "name" : "Sara",
        "age" : 16
    ],
    [
        "name" : "Leo",
        "age" : 8
    ]
]

var friendsSortedByAge: [[String : Any]] = [[:]]
var tempArrayOfAges: [Int] = []

for friend in friends {
    if let age = friend["age"] as? Int {
        tempArrayOfAges.append(age)
    }
}

tempArrayOfAges.sort()

for friend in friends {
    for n in 0..<tempArrayOfAges.count {
        if let age = friend["age"] as? Int {
            if age == tempArrayOfAges[n] {
                friendsSortedByAge.insert(friend, at: n)
            }
        }
    }
}

print(tempArrayOfAges)
print(friendsSortedByAge)
pacification
  • 5,838
  • 4
  • 29
  • 51
Ele
  • 11
  • 2
  • Possible duplicate of [Swift how to sort array of custom objects by property value](https://stackoverflow.com/questions/24130026/swift-how-to-sort-array-of-custom-objects-by-property-value) – Ele Jul 27 '18 at 09:18

1 Answers1

1

You cannot insert objects at indices greater than the number of objects in the array. After sorting the ages array the indices aren't in sync anymore and this causes the exception.

However you can sort the array in a much easier (and error-free) way

let friends = [
    [
        "name" : "Alex",
        "age" : 23
    ],
    [
        "name" : "Massi",
        "age" : 38
    ],
    [
        "name" : "Sara",
        "age" : 16
    ],
    [
        "name" : "Leo",
        "age" : 8
    ]
]

let friendsSortedByAge = friends.sorted(by: {($0["age"] as! Int) < $1["age"] as! Int})
print(friendsSortedByAge)
vadian
  • 274,689
  • 30
  • 353
  • 361
  • Yes, this is much easier and error-free thanks! So the problem before was that I was trying to insert an object in an empty array and the index didn't exist? – Ele Jul 26 '18 at 11:55
  • Yes, only the indices `0...array.count` are valid. – vadian Jul 26 '18 at 12:05