提问者:小点点

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


例如,我有一个数组:

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

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

例如,01/02/16 出现在索引 03 处。02/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个答案

匿名用户

试试这个

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

希望这有帮助