我无法在数组中获得可重复的字符串位置。我的代码是这样的:
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]
执行此操作的正确代码是什么?
答案 0 :(得分:5)
您想要与特定日期匹配的项目的索引,因此请过滤索引:
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]
答案 1 :(得分:0)
let date = "06/11/2018"
var matchingIndices = [Int]()
for (index, startDate) in startDates.enumerated() {
if date == startDate {
matchingIndices.append(index)
}
}
您要遍历列表一次,注意匹配的索引。这应该符合您的预期输出。