I’m would like to get some help wrapping my head around simplifying this code. This works but I’m thinking there Must be a simpler way.
Goal:
- Replace all VirtualRide w/ Ride
- If Both VirtualRide and Ride exists in array, remove VirtualRide
eg:
input = ["Ride", "VirtualRide", "Run", "VirtualRun"] expected output = ["Ride", "Run"]
input = ["VirtualRide", "VirtualRun"] expected output = ["Ride", "Run"]
input = ["Ride", "Run"] expected output = ["Ride", "Run"] (Basically do nothing)
This is the current code that works, but is just seems ugly and long.
let sportsArray = ["Ride", "VirtualRide"]
var newSportsArray = sportsArray // sportsArray is passed in. So it's a Let
let ixVirtualRide = sportsArray.firstIndex(of: "VirtualRide")
if let ixVirtualRide = ixVirtualRide {
if newSportsArray.filter({$0.contains("Ride")}).count > 1 {
newSportsArray.remove(at: ixVirtualRide)
}
if newSportsArray.filter({$0.contains("VirtualRide")}).count == 1 {
newSportsArray.remove(at: ixVirtualRide)
newSportsArray.append("Ride")
}
}
3
Answers
If the goal is to remove any Virtual occurrence, delete the substring if matched:
Then, if the array cannot contain anything else than those four elements, use a set to clear duplicates:
Here we import OrderedCollections from the Swift package library because we want to use an Ordered set to remove duplicates but maintain order:
If Virtual isn’t always at the start, and never appears anywhere else, you can use replacingOccurrences(of:) otherwise a handy extension on String helps here:
Now we can make a function that takes the array of strings and removes the prefixes and deduplicates the results, maintaining the order of them.
Then
etc for all your example inputs.
If you prefer this style you can write it like this too:
Which might be handy if you have a use for the "Virtual" prefix deleter function in other places.
The other approach that suggests itself is to standardise your input via an enum (essentially parsing it), like:
Your specifications are incomplete and don’t match your examples. I guess you want to
Virtual
Ride
fromVirtualRide
if there is anotherRide
)["Ride", "Run"]
)Below code will still work when you introduce
VirtualLift
: