【发布时间】:2019-01-02 06:11:12
【问题描述】:
我正在尝试按年龄对这组字典进行排序。 当我尝试遍历朋友数组(最后一个 for in 循环)并在特定索引处插入时,我收到一个致命错误:
插入元素时数组索引超出范围。
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)
【问题讨论】:
标签: arrays swift sorting for-loop