如何按值对自定义数组的行进行排序?

时间:2019-11-13 20:43:30

标签: arrays swift

我有一个需要按此顺序排列的数组值

let daysOfWeekArray = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]

目前我的数组看起来像这样

let allData = [CustomObject(day:"Tuesday", startTime: "5:00"), CustomObject(day:"Sunday", startTime: "3:00")]
array.append(allData)

如何获取按天排序的数组?

很抱歉,这似乎是一个简单的问题,是对数组进行排序的新手。

3 个答案:

答案 0 :(得分:2)

您可以在参考数组中查找当天的索引并按该索引值排序

array.sort(by: { 
    (daysOfWeekArray.firstIndex(of: $0.day) ?? Int.max) < (daysOfWeekArray.firstIndex(of: $1.day) ?? Int.max)})

我使用Int.max,以防找不到日期,以便该元素排在最后。

另一方面,可以从属性Calendar的{​​{1}}类中获取用于订购的数组,因此可以通过直接使用该属性来进行排序

weekDaySymbols

当然,您需要确保为日历使用正确的语言环境。

答案 1 :(得分:0)

也许不是最好的解决方案,但是看起来可行。

let daysOfWeekArray = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]

struct CustomObject {
    var day: String
    var startTime: String
}

let allData = [CustomObject(day:"Tuesday", startTime: "5:00"), CustomObject(day:"Friday", startTime: "3:00"), CustomObject(day:"Sunday", startTime: "3:00"), CustomObject(day:"Monday", startTime: "3:00")]

let sorted = allData.sorted { (a, b) -> Bool in
    let aIndex = daysOfWeekArray.firstIndex(of: a.day)!
    let bIndex = daysOfWeekArray.firstIndex(of: b.day)!
    if aIndex > bIndex {
        return false
    } else {
        return true
    }
}
print(sorted)

答案 2 :(得分:0)

如果我是你,我会像这样将这些字符串更改为枚举:

enum DayOfWeek {
    case sunday
    case monday
    case tuesday
    case wednesday
    case thursday
    case friday
    case saturday

    var title: String {
        switch self {
        case .sunday:       return "Sunday"
        case .monday:       return "Monday"
        case .tuesday:      return "Tuesday"
        case .wednesday:    return "Wednesday"
        case .thursday:     return "Thursday"
        case .friday:       return "Friday"
        case .saturday:     return "Saturday"
        }
    }

    var dayInWeek: Int {
        switch self {
        case .sunday:       return 0
        case .monday:       return 1
        case .tuesday:      return 2
        case .wednesday:    return 3
        case .thursday:     return 4
        case .friday:       return 5
        case .saturday:     return 6
        }
   }

    static var all: [DayOfWeek] {
       return [.sunday, .monday, .tuesday, .wednesday, .thursday, .friday, .saturday] 
    }
}
struct CustomObject {
    let day: DayOfWeek
    let startTime: String
    // ....
}

let daysOfWeekArray = DayOfWeek.all

let allData = [CustomObject(day:.tuesday, startTime: "5:00"), CustomObject(day:.sunday, startTime: "3:00")]
var array: [CustomObject] = []
array.append(contentsOf: allData)
array = array.sorted { $0.day.dayInWeek < $1.day.dayInWeek }
print(array.map{$0.day.title})