長期解決方案
sampleArray
迭代自身並在退出循環之前刪除正在查找的值(如果它存在)。
var sampleArray = ["Hello", "World", "1", "Again", "5"]
let valueToCheck = "World"
for (index, value) in sampleArray.enumerated() {
if value == valueToCheck && sampleArray.contains(valueToCheck) {
sampleArray.remove(at: index)
break
}
}
print(sampleArray) // Returns ["Hello", "1", "Again", "5"]
簡短的解決方案
sampleArray
返回不等於你正在檢查的所有數值的數組。
var sampleArray = ["Hello", "World", "1", "Again", "5"]
let valueToCheck = "World"
sampleArray = sampleArray.filter { $0 != valueToCheck }
print(sampleArray) // Returns ["Hello", "1", "Again", "5"]
感謝您的建議,但這裏沒有'index(of:)'的參數。它應該是什麼? –
再次看看我的示例,您會看到它是* currNr *字符串的索引。 – Lawliet
'index(of:)'只存在符合'Equatable'的對象https://developer.apple.com/documentation/swift/equatable – iwasrobbed