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)
1

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

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?
Yes, only the indices 0...array.count are valid.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.