首页 > 解决方案 > 如果我有多个具有相同值的元素,如何从数组中删除单个元素?

问题描述

如果我有这样的数组,如果我不能使用 .remove(at:),我怎么能只删除 4:rs 之一:

let a = [3, 4, 4, 5, 4, 8, 7]

标签: arraysswift

解决方案


您需要获取 value = 4 的第一个元素的索引,然后将其删除。这是代码:

import Foundation

var a = [3, 4, 4, 5, 4, 8, 7]
let b = a.firstIndex(of: 4)
if let b = b {
a.remove(at: b)
} else { 
print("value not present in array")
}
print(a)

推荐阅读