iOS swift : Track and store indices of all duplicate values in an array?

标签 ios arrays swift

我最近问了这个问题:iOS Swift: How to store the index of all duplicate values in array?

我得到了我的问题的确切答案,但我发现我无法使用它来实现我在代码中需要的东西。

我正在尝试存储 Date 数组的任何重复值的所有索引,并存储在另一个数组 [ [Int] ] 中。

例如,这是我的 Date 数组:

let dates = [2016-01-02 08:00:00 +0000, 2016-01-02 08:00:00 +0000,
             2016-02-02 08:00:00 +0000, 2016-03-02 08:00:00 +0000, 
             2016-05-01 08:00:00 +0000, 2016-05-01 08:00:00 +0000]

我正在尝试做的,与我之前的问题类似,是将所有重复的 Date 值的所有索引存储到一个单独的数组中。

例如,下面的数组将包含:

repeatedIndices = [ [0, 1], [2], [3], [4, 5] ]

其中索引 01 包含重复日期 2016-01-02 08:00:00 +0000 和索引 45 包含重复的日期 2016-05-01 08:00:00 +0000

我之前的问题在 [ String: [Int] ] 中提供了答案,作为初学者,我不知道如何操纵它来使用我的代码,因为字典是无序,我需要一个有序数组。

如有必要,请标记为重复,但我不想编辑问题并取消标记答案,因为这不公平。

谢谢。

最佳答案

使用带有示例值的[Date:[Int]] 字典,

var duplicatedDict : [Date:[Int]] = [:]

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

debugPrint(duplicatedDict)

到目前为止,控制台中的结果非常好

[2016-02-02 08:00:00 +0000: [2], 2016-05-01 08:00:00 +0000: [5, 6], 2016-03-02 08:00:00 +0000: [3, 4], 2016-01-02 08:00:00 +0000: [0, 1]]

然后我们需要循环排序的字典键并将每个键数组中的值添加到数组

func returnValuesOrdered() ->[[Int]]{

        var result : [[Int]] = []

        for key in duplicatedDict.keys.sorted(by: {$0 < $1})
        {
            result.append(duplicatedDict[key]!)
        }

        debugPrint(result)
        return result
    }

控制台结果

[[0, 1], [2], [3, 4], [5, 6]]

希望对你有帮助

关于iOS swift : Track and store indices of all duplicate values in an array?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45537650/

相关文章:

iphone - 使用 FQL/Graph API 获取地点推荐和喜欢某个地点的人员列表

ios - 使用 -> present(viewControllerToPresent : UIViewController, animated : true, completion: nil) 调用后 rootViewController 未加载

Java - 是否可以对数组进行子类化?还有更多关于 Java 数组的问题

ios - 如何处理在粘贴到 Xcode 时出现 "unprintable ascii character found in source file"错误的用户输入字符串?

ios - 在更新 iOS 程序注册 ID 时丢失

ios - 方法可能缺少 [super dealloc] 调用

java - java如何删除一个数字到数组中?

java - 将数组减半,填充它,然后重新减半

iOS 自定义 View - 非常奇怪的属性行为

swift - 水平 CollectionView 间距无法正常工作 Swift