arrays - 如果我有多个具有相同值的元素,如何从数组中删除单个元素?
问题描述
如果我有这样的数组,如果我不能使用 .remove(at:),我怎么能只删除 4:rs 之一:
let a = [3, 4, 4, 5, 4, 8, 7]
解决方案
您需要获取 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)
推荐阅读
- json - 如何使用 JSON.Net 获取 JSON 文件中的所有子节点
- android - Firebase 存储图像显示问题
- nginx - 在 nginx 上使用 kerberos 时如何禁用基本身份验证?
- python - Gunicorn:多个后台工作线程
- visual-studio-code - 如何避免 VS Code 和 vscodevim 之间的键绑定冲突?
- ruby-on-rails - 除非在检查布尔值时进行验证,否则更清洁
- java - 读取程序集时出错:带 ID 的描述符
未找到 - python - 标签编码是否由 sklearn SVC 自动完成?
- json - 如何使用 mule3 中的转换消息过滤来自数据库连接器的输出 json
- git - 在 Heroku 上使用 git 部署大文件的最佳方法是什么?