有什么方法可以对数组中的自定义对象进行排序?

时间:2019-04-06 12:03:52

标签: swift swift4

我有这个数组

var bookTimeArray = [BookTime]()

BookTime类包含以下内容

var time : String = ""
var status : String = ""
var booked_by : String = ""

现在,我需要通过查看BookTime.time变量来对数组bookTimeArray进行排序。

时间变量可能包含从“ 12AM”到“ 11PM”的时间

对象需要按照以下模式排序

["12AM", "1AM", "2AM", "3AM", "4AM", "5AM", "6AM", "7AM", "8AM", "9AM", "10AM", "11AM", "12PM", "1PM", "2PM", "3PM", "4PM", "5PM", "6PM", "7PM", "8PM", "9PM","10PM", "11PM"]

如果bookTimeArray有5个对象

bookTimeArray[0].time = "10AM"
bookTimeArray[1].time = "6AM"
bookTimeArray[2].time = "9AM"
bookTimeArray[3].time = "6PM"
bookTimeArray[4].time = "9PM"

预期产量

bookTimeArray[0].time = "6AM"
bookTimeArray[1].time = "9AM"
bookTimeArray[2].time = "10AM"
bookTimeArray[3].time = "6PM"
bookTimeArray[4].time = "9PM"

我不知道如何实现这一目标。帮帮我:(

3 个答案:

答案 0 :(得分:0)

您可以这样做:

// First create a DateFormatter object to convert your time strings to Date objects so you can compare between them.
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "ha"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")

// Then you only need to sort the bookTimeArray by *time* property after converting *time* string to a Date object using the dateFormatter that we've created above.
let sortedBooks = bookTimeArray.sorted { dateFormatter.date(from: $0.time)! < dateFormatter.date(from: $1.time)! }

答案 1 :(得分:0)

您可以使用dateFormatter通过Date属性创建String对象,然后可以按这些Date s对数组进行排序

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "ha" // format 1AM, 2AM, 12PM, ...
dateFormatter.locale = Locale(identifier: "en_US_POSIX")

排序:

bookTimeArray.sort { bookTime1, bookTime2 in
    guard let date1 = dateFormatter.date(from: bookTime1.time), let date2 = dateFormatter.date(from: bookTime2.time) else { return false }
    return date1 < date2
}

答案 2 :(得分:0)

希望这会有所帮助:

// Custom models array   
 let dataArray = [Class(fileID:1),Class(fileID:2),Class(fileID:3)]
// here is sorting code
    dataArray.sorted({ $0.fileID > $1.fileID })