在這段代碼中,當迭代位置達到 20 個元素的陣列中的第 13 個時,它會因索引超出范圍錯誤而崩潰。
let counterHeaders = headers.count
for value in 0..<(counterHeaders){
if headers[value] == "" {
headers.remove(at: value)
}
}
注意:創建 counterHeaders 變數是為了檢查 headers 陣列中有多少值
uj5u.com熱心網友回復:
洗掉集合中的專案時,您只需要以indices相反的順序迭代您的。
for value in headers.indices.reversed() {
if headers[value] == "" {
headers.remove(at: value)
}
}
另請注意,有一個變異方法接受稱為謂詞removeAll(where:):
headers.removeAll(where: \.isEmpty)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/416302.html
標籤:
