This answer picks up on the refinement to the question in the below comment from the OP in response to the answer from @vadian. The actual requirement is to sort football goal times provided by the API. The solution below creates a struct for this data with a calculated variable for actual goal time and then sorts by that.
struct Goal{
let matchDate: String
let matchTime: String
let goalTime: String
var timeOfGoal: Date {
let goalComponents = goalTime.components(separatedBy: "+").map{$0.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines.union(CharacterSet.decimalDigits.inverted))}
let goalSeconds = TimeInterval(60 * goalComponents.compactMap({Int($0)}).reduce(0, +))
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
let startTime = dateFormatter.date(from: matchDate + " " + matchTime)!
return startTime.addingTimeInterval(goalSeconds)
}
}
I tested this as below
let goals = [
Goal(matchDate: "2019-11-18", matchTime: "22:00", goalTime: "90 +7"),
Goal(matchDate: "2019-11-18", matchTime: "19:00", goalTime: "22"),
Goal(matchDate: "2019-11-18", matchTime: "22:00", goalTime: "99"),
Goal(matchDate: "2019-11-18", matchTime: "19:00", goalTime: "45 + 3"),
Goal(matchDate: "2019-11-18", matchTime: "19:00", goalTime: "45+6"),
Goal(matchDate: "2019-11-18", matchTime: "22:00", goalTime: "90+6"),
Goal(matchDate: "2019-11-18", matchTime: "22:00", goalTime: "35"),
Goal(matchDate: "2019-11-18", matchTime: "22:00", goalTime: "85"),
Goal(matchDate: "2019-11-18", matchTime: "22:00", goalTime: "90"),
Goal(matchDate: "2019-11-18", matchTime: "22:00", goalTime: "90+ 8"),
Goal(matchDate: "2019-11-18", matchTime: "19:00", goalTime: "44")]
let ordered = goals.sorted{$0.timeOfGoal > $1.timeOfGoal}
ordered.forEach{print("\($0.matchDate) - \($0.matchTime) - \($0.goalTime) ")}
and it correctly produced:
2019-11-18 - 22:00 - 99
2019-11-18 - 22:00 - 90+ 8
2019-11-18 - 22:00 - 90 +7
2019-11-18 - 22:00 - 90+6
2019-11-18 - 22:00 - 90
2019-11-18 - 22:00 - 85
2019-11-18 - 22:00 - 35
2019-11-18 - 19:00 - 45+6
2019-11-18 - 19:00 - 45 + 3
2019-11-18 - 19:00 - 44
2019-11-18 - 19:00 - 22
There is room for improvement by not force unwrapping the Date?
, although the string cleaning makes this reasonably safe, and by using a class-level static DateFormatter. But I'll leave that refinement for the implementation :-)