Swift致命错误:插入元素时数组索引超出范围

时间:2018-07-25 12:14:51

标签: arrays swift sorting for-loop

我正在尝试按年龄对这组词典进行排序。 当我尝试遍历朋友数组(最后一次循环)并插入特定索引时,出现致命错误:

  

插入元素时数组索引超出范围。

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 个答案:

答案 0 :(得分:1)

您不能以大于数组中对象数的索引插入对象。对ages数组进行排序后,索引不再同步,这将导致异常。

但是,您可以以更简单(且无错误)的方式对数组进行排序

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)