Arrays 在数组中查找可重复的字符串位置

Arrays 在数组中查找可重复的字符串位置,arrays,swift,string,Arrays,Swift,String,我无法在数组中获得可重复的字符串位置。我的代码如下: 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: .c

我无法在数组中获得可重复的字符串位置。我的代码如下:

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, 3]
结果是:

nomornya:[0, 0, 0, 0]
我想要这样:

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, 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]

您希望在列表中迭代一次,并记录匹配的索引。这应该与您的预期输出相匹配。

如果有多个重复的日期,那么输出会是什么?功能是从日历中获取所有事件,哪一个日期可以有多个事件标题,因此我必须获取位置您在这里尝试做什么?这些字符串看起来像日期,但您将它们作为字符串处理。看起来可能有更好的方法来做你想做的事情。
[“06/11/2018”,“16/11/2018”,“26/11/2018”,“06/11/2018”,“16/11/2018”]
?@Sweeper结果必须是[0,3]这一个也是正确的,但代码更长