Im trying to use this line of code:
func getFirstWeekDay() -> Int {
let day = ("\(currentYear)-\(currentMonthIndex)-01".date?.firstDayOfTheMonth.weekday)!
return day
}
but Im getting this error.. I dont know how else to write it.
Error: Cannot use optional chaining on non-optional value of type 'Any'
You have several errors. Where did you get the code from ?
First, you look for dtae property of a string :
"a string".date
There is no such property
Where did you define firstDayOfTheMonth ?
To get the date from a string, should use dateFormatter as here:
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let currentYear = 2020
let currentMonthIndex = "01"
let day = dateFormatter.date(from: "\(currentYear)-\(currentMonthIndex)-01")!
You set the day as 01. What the use to search for firstDaysOfTheMonth ?
You could also build the date through its components
let calendar = Calendar.current
var components = DateComponents()
components.day = 1
components.month = 1
components.year = 2020
let newDate = calendar.date(from: components)!
Then you can get weekDay
components = calendar.dateComponents([.day, .month, .year, .weekday], from: newDate)
print("weekday:\(components.weekday!)")
So, your func should become:
func getFirstWeekDay() -> Int {
var components = DateComponents()
components.day = 01
components.month = currentMonthIndex
components.year = currentYear
let theDate = calendar.date(from: components)!
components = calendar.dateComponents([.weekday], from: theDate)
return components.weekday!
}
I advise you study Date class. This tutorial may help.
h ttp://ios-tutorial.com/working-dates-swift/