Reputation: 649
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?
Upvotes: 0
Views: 100
Reputation: 4006
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:
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) }
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])
}
Upvotes: 1