【问题标题】:How to move array object to first index如何将数组对象移动到第一个索引
【发布时间】:2021-12-15 09:52:36
【问题描述】:

如何将数组对象带到第一个索引

   struct ScheduleDateTime {
     var startDate: String?
     var endDate: String?
     var isScheduled: Bool?
    }

var scheduleDateTime = [ScheduleDateTime]()
    func reArrange(){
        if let scheduleList = scheduleDateTime{
          if  scheduleList.count > 1 {
              for each in scheduleList {
                  if each.isScheduled == true {
                    // Bring the item to first Index.

                  }
              }
            } 
        }
    }

如何根据上述isSchedule == true 条件将数组索引置于首位

【问题讨论】:

  • for 0..

标签: ios arrays swift


【解决方案1】:

您可以在比较isScheduled 的基础上做一个sort。这会将所有 isScheduled == true 项移动到数组的前面。

let input : [ScheduleDateTime] = 
  [.init(startDate: "Item1", endDate: nil, isScheduled: false),
   .init(startDate: "Item2", endDate: nil, isScheduled: false),
   .init(startDate: "Item3", endDate: nil, isScheduled: true),
   .init(startDate: "Item4", endDate: nil, isScheduled: false),
   .init(startDate: "Item5", endDate: nil, isScheduled: true)]

let output = input.sorted(by: { $0.isScheduled == true && $1.isScheduled != true })

print(output.map(\.startDate!))

产量:

[“项目 3”、“项目 5”、“项目 1”、“项目 2”、“项目 4”]

【讨论】:

    猜你喜欢
    • 2020-07-27
    • 2016-09-27
    • 2019-11-08
    • 2018-07-31
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    相关资源
    最近更新 更多