I am building an app that gives you the option to sort a list of fuels available at different gas stations by cheapest, nearest location and cheapest nearby. However, I don't know what the correct code for the last one would be. My code is looking like this right now:
switch searchMode {
case .queryByNearby:
orderedList.sort { $0.distance < $1.distance }
case .queryByCheapest:
orderedList.sort { $0.price < $1.price }
case .queryByCheapestNearby:
orderedList.sort { $0.price < $1.price && $0.distance < $1.distance }
}
is there any way I can do this?
CodePudding user response:
As some of the comments have already mentioned, in 3rd case "cheapest nearby" you need to decide what has higher priority, price or distance. Based on that following solutions can be implemeted.
If price has higher priority
switch searchMode {
case .queryByNearby:
orderedList.sort { $0.distance < $1.distance }
case .queryByCheapest:
orderedList.sort { $0.price < $1.price }
case .queryByCheapestNearby:
orderedList.sort { $0.price == $1.price ? $0.distance < $1.distance : $0.price < $1.price }
}
If distance has higher priority
switch searchMode {
case .queryByNearby:
orderedList.sort { $0.distance < $1.distance }
case .queryByCheapest:
orderedList.sort { $0.price < $1.price }
case .queryByCheapestNearby:
orderedList.sort { $0.distance == $1.distance ? $0.price < $1.price : $0.distance < $1.distance }
}
You you could implement both and give 4 options to the user.