Home > other >  How to convert two dimensional array into separate array
How to convert two dimensional array into separate array

Time:02-27

I try to get days of week from calendar and get the value from it so I can store in object, but I get confused how can I transform the array so I can save in struct. This is how I can get the days of week

let calendar = Calendar.current
let dayOfWeek = calendar.component(.weekday, from: dateInWeek)
let weekdays = calendar.range(of: .weekday, in: .weekOfYear, for: dateInWeek)!
let days = (weekdays.lowerBound ..< weekdays.upperBound)
    .compactMap { calendar.date(byAdding: .day, value: $0 - dayOfWeek, to: dateInWeek) }

and then I format it to get the day and the date number

let formatter = DateFormatter()
formatter.dateFormat = "E d"

This is the output of my date

let strings = days.map { formatter.string(from: $0) }
print(strings)

["Sun 27", "Mon 28", "Tue 1", "Wed 2", "Thu 3", "Fri 4", "Sat 5"]

This is the struct how I want to store separately from day and date number

struct Week {
    let dayName: String
    let dayDate: String
}

I already try this method but the days turn into two dimensional array

for week in strings {
    let weeks = week.components(separatedBy: " ")
    print(weeks)
}

How can I turn the two dimensional array so I can store in struct?

CodePudding user response:

If I understood well what you want:

You don't need to parse your array, you can create your struct from the data provided initially to the array. This means:

  1. Create 2 new arrays almost identical to the one you showed above, but each one of them will store different data - one with the dayName and the other one with the dayDate. You just need to create these arrays by changing your formatter:
let formatterWeek = DateFormatter()
formatterWeek.dateFormat = "E"     // For your first array
let weekDays = days.map { formatterWeek.string(from: $0) }

let formatterDays = DateFormatter()
formatterDays.dateFormat = "d"     // For your second array
let daysDates = days.map { formatterDays.string(from: $0) }
  1. Iterate through the arrays to create your struct instances (adapt this part of the code to your needs):
for index in 0..<weekDays.count {
    let _ = Week(dayName: weekDays[index],         // Store this instance to any variable or array you want
                 dayDate: daysDates[index])
}
  • Related