如何找到数组中重复项的索引

时间:2019-05-10 03:09:11

标签: arrays swift

我有一个with图,我还需要从数组和“ 0”中删除重复值,并且我想根据该值来调整数组


extension Array where Element: Equatable {
    var unique: [Element] {
        var uniqueValues: [Element] = []
        forEach { item in
            if !uniqueValues.contains(item) {
                uniqueValues += [item]
            }
        }
        return uniqueValues
    }
}

let speed = [0, 10, 20, 20, 40, 50, 50 ,50, 80, 90, 100]
let time = ["9", "10", "11", "12", "13", "15", "16", "17", "18", "19", "20"]

speed.unique // Return Only Unique Values 

现在我希望更新时间序列。 例 索引:0、3-已从速度中删除 我也想同时删除索引0、3

1 个答案:

答案 0 :(得分:2)

您可以这样做:

let speed = [  0,   10,   20,   20,   40,   50,   50,   50,   80,   90,  100]
let time =  ["9", "10", "11", "12", "13", "15", "16", "17", "18", "19", "20"]

var sp = [Int]()
var tm = [String]()

for (i, x) in speed.enumerated() {
    if !sp.contains(x) {
        sp.append(x)
        tm.append(time[i])
    }
}

print(sp) //[  0,   10,   20,   40,   50,   80,   90,  100]
print(tm) //["9", "10", "11", "13", "15", "18", "19", "20"]

建议为time选择适当的类型。

在面向对象的编程中,建议将速度和时间作为结构的属性:

struct Mover {
    let speed: Int
    let time : TimeInterval
}

例如给出以下数组:

let movers = [Mover(speed:   0, time:  9),
              Mover(speed:  10, time: 10),
              Mover(speed:  20, time: 11),
              Mover(speed:  20, time: 12),
              Mover(speed:  40, time: 13),
              Mover(speed:  50, time: 15),
              Mover(speed:  50, time: 16),
              Mover(speed:  50, time: 17),
              Mover(speed:  80, time: 18),
              Mover(speed:  90, time: 19),
              Mover(speed: 100, time: 20)]

您可以通过以下方式使元素保持独特的速度:

var speeds = Set<Int>()

let moversUniqueSpeed = movers.filter { speeds.insert($0.speed).inserted }