在Swift中,可以使用NSSortDescriptor按日期的月份对数据进行排序。下面是一个示例代码:
import Foundation
struct Person {
var name: String
var birthday: Date
}
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let person1 = Person(name: "John", birthday: dateFormatter.date(from: "1990-03-15")!)
let person2 = Person(name: "Jane", birthday: dateFormatter.date(from: "1985-07-20")!)
let person3 = Person(name: "Mike", birthday: dateFormatter.date(from: "1995-01-10")!)
let people = [person1, person2, person3]
let sortDescriptor = NSSortDescriptor(key: "birthday", ascending: true, comparator: { (date1, date2) -> ComparisonResult in
let calendar = Calendar.current
let month1 = calendar.component(.month, from: date1 as! Date)
let month2 = calendar.component(.month, from: date2 as! Date)
if month1 < month2 {
return .orderedAscending
} else if month1 > month2 {
return .orderedDescending
} else {
return .orderedSame
}
})
let sortedPeople = (people as NSArray).sortedArray(using: [sortDescriptor]) as! [Person]
for person in sortedPeople {
print("\(person.name): \(dateFormatter.string(from: person.birthday))")
}
在这个示例中,我们创建了一个Person结构体来保存人员的姓名和生日。然后使用DateFormatter将字符串转换为日期对象。
接下来,我们创建了三个人员对象,并将它们存储在一个数组中。
然后,我们创建了一个NSSortDescriptor对象,并使用自定义的比较器来比较日期的月份。比较器通过Calendar.current获取日期的月份,并根据月份的大小来进行排序。
最后,我们使用sortedArray(using:)方法将数组按照NSSortDescriptor进行排序,并将结果转换回原始的Person对象数组。
最后,我们遍历排序后的人员数组,并打印每个人员的姓名和生日。
输出结果将按照日期的月份进行排序。