gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:47:05 25 4
gpt4 key购买 nike

我有这个数组

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"

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

最佳答案

你可以这样做:

// 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)! }

关于swift - 有什么方法可以对数组内的自定义对象进行排序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55548885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com