0

How to bring array object to first Index

   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.

                  }
              }
            } 
        }
    }

How to bring the array Index to first position based on above isSchedule == true condition

1
  • for 0..<scheduleDateTime.count { let oldSchedule = scheduleDateTime[0] let isScheduled = oldSchedule.isScheduled if isScheduled { scheduleDateTime.removeAtIndex(i) let newSchedule = ScheduleDateTime(startDate: oldSchedule.startDate, oldSchedule.endDate, true) scheduleDateTime.insert(newSchedule, at: 0) } } Commented Oct 31, 2021 at 4:43

1 Answer 1

1

You can do a sort based on comparing isScheduled. This will move all isScheduled == true items to the front of the array.

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

Yields:

["Item3", "Item5", "Item1", "Item2", "Item4"]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.