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)