I am having a with graph, i need to remove duplicates values from array and "0" as well and i want to adjust array according to that for example
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
Now i want my time array to be updated. Example Index : 0, 3 - is removed from speed i want to remove index 0, 3 from time as well
1 Answer 1
You can do it this way:
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"]
Choosing an appropriate type for time
is advisable.
It is recommended in object-oriented programming to have speed and time as properties of a struct:
struct Mover {
let speed: Int
let time : TimeInterval
}
For example given this array:
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)]
You could keep the elements with a unique speed this way:
var speeds = Set<Int>()
let moversUniqueSpeed = movers.filter { speeds.insert(0ドル.speed).inserted }
answered May 10, 2019 at 3:46
1 Comment
istorry
i am so dumb why didn't i thought about this, Thank you very much.
lang-swift
struct
where thestruct
hasspeed
andtime
properties. Then you much more easily sort and filter the array of struct. When done you could create the two final arrays from the final array ofstruct
.