【问题标题】:iOS Swift: How to store the index of all duplicate values in array?iOS Swift:如何将所有重复值的索引存储在数组中?
【发布时间】:2018-01-14 04:28:58
【问题描述】:

我们以我有这个数组为例:

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")
}

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

【问题讨论】:

    标签: ios arrays swift


    【解决方案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]]

    希望对你有帮助

    【讨论】:

    • @Reinier..另一个问题,因为字典没有“顺序”的意义......我怎样才能将索引数组附加到另​​一个根据@的顺序排序的数组中987654322@ 数组?....例如[ [0,1], [2], [3] ] 之类的东西,它对应于最初在dates 数组中的顺序....或者甚至只是消除[ String: [Int] ] 配对在一起,只有[ [Int] ]
    • 您可以订购您的钥匙并返回您订购的钥匙的值,但首先您需要转换为日期才能返回正确的顺序
    • @对不起,我是这方面的初学者。我不确定你的意思,你能在你的答案下面附上一个例子吗?
    • @Pangu 你可以再添加一个问题,这样更好,因为其他人可以发布他们的解决方案,也许我也从中学习
    • @Pangu 如果您发布其他问题,请告诉我
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-23
    • 2018-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-08
    相关资源
    最近更新 更多