首页 > 解决方案 > 在数组中找到可重复的字符串位置

问题描述

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

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]

这样做的正确代码是什么?

标签: arraysswiftstring

解决方案


您希望项目的索引与特定日期匹配,因此过滤索引:

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]

推荐阅读