arrays - 在数组中找到可重复的字符串位置
问题描述
我无法在数组中获得可重复的字符串位置。我的代码是这样的:
var startDates : [String] = ["06/11/2018", "16/11/2018", "26/11/2018", "06/11/2018"]
var nomor : [Int] = []
for date in startDates {
if startDates.contains(where: {
$0.range(of: "06/11/2018", options: .caseInsensitive) != nil
}) == true {
let nomornya = startDates.index(of: "06/11/2018")!
nomor.append(nomornya)
}
}
print("nomornya:\(nomor)")
结果:
nomornya:[0, 0, 0, 0]
我想要这样:
nomornya:[0, 3]
这样做的正确代码是什么?
解决方案
您希望项目的索引与特定日期匹配,因此过滤索引:
let startDates = ["06/11/2018", "16/11/2018", "26/11/2018", "06/11/2018"]
let nomor = startDates.indices.filter{ startDates[$0] == "06/11/2018" } // [0, 3]
推荐阅读
- python - Python函数通过记忆返回不同的结果
- .net - 用于桌面应用程序的受 OpenID Connect 保护的 API
- r - 无法使用 R Shiny 中的 DT 包取消选择代理选择的行
- c# - 我的 C# 程序正在使用过多的内存(BinaryReader 来缓冲)
- php - PHP 从 html 文件中提取特定标签之间的数据
- ios - iOS Swift - 从设置打印到标签
- node.js - AWS Elastic beanstalk 上的 Google 日历身份验证
- c++ - 为什么 Boost Variant 使用模板构造函数而不是 boost::beast::websocket::stream 的移动构造函数?
- r - 在 reticulate::use_condaenv(path) 之后无法弄清楚如何使用 conda 环境
- javascript - 条款和条件的复选框验证