iOS Swift:如何在数组中存储所有重复值的索引?

时间:2017-08-06 22:26:01

标签: ios arrays swift

让我们举个例子,我有这个数组:

let dates = ["01/02/16", "02/02/16", "03/02/16", "01/02/16", "02/02/16"]

我喜欢做的是将每个String日期存储在字典中作为键,对于每个重复的键,我喜欢将其索引存储为数组,并将其与重复键相关联

例如,01/02/16出现在索引0302/02/16发生在索引14

我喜欢这样的词典:

[ "01/02/16": [0, 3], "02/02/16": [2, 4], "03/02/16": [1] ]

我知道如何跟踪有多少重复条目:

let dates = ["01/02/16", "01/02/16", "02/02/16", "03/02/16"]

var dateCounts:[String:Int] = [:]

for date in dates
{
    dateCounts[date] = (dateCounts[date] ?? 0) + 1

}

for (key, value) in dateCounts
{
    print("\(key) occurs \(value) time/s")
}

但是,我不确定如何跟踪重复索引?

1 个答案:

答案 0 :(得分:2)

试试这个

import UIKit

class ViewController: UIViewController {

    var duplicatedDict : [String:[Int]] = [:]
    let dates = ["01/02/16", "01/02/16", "02/02/16", "03/02/16"]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        for (index,dateString) in dates.enumerated() {
            if(duplicatedDict[dateString] == nil){
                duplicatedDict[dateString] = [index]
            }else{
                duplicatedDict[dateString]?.append(index)
            }
        }

        debugPrint(duplicatedDict)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

控制台日志输出

  

[“02/02/16”:[2],“01/02/16”:[0,1],“03/02/16”:[3]]

希望这有帮助