I am still relatively new to swift, so I am having some problems with the proper syntax. Here is my code for the class Date, which has the isLeapYear and daysInMonth methods. I am having problems with the optionals for these methods:
class Date {
var day, month, year : Int
init (day : Int, month : Int, year : Int) {
self.day = day
self.month = month
self.year = year
}
func isLeapYear(y : Int? = self.year) -> Bool {
var x = false
if y % 4 == 0 {x = true}
return x
}
//Returns the amount of days in a given month
func daysInMonth(month : Int? = self.month, year : Int? = self.year) -> Int? {
let _31_day_months = [1, 3, 5, 7, 8, 10, 12]
let _30_day_months = [4, 6, 9, 11]
if month == 2 {
if self.isLeapYear(y : year) {return 29} else {return 28}
}
else if _31_day_months.contains(month) {return 31}
else if _30_day_months.contains(month) {return 30}
else {return nil}
}
}
What I want to do with func isLeapYear(y : Int? = self.year) -> Bool
is that when I call isLeapYear and y isn't specified, that it is automatically set to self.year. However I get the following error:
use of unresolved identifier 'self'
I also get the error
value of optional type 'Int?' must be unwrapped to a value of type 'Int'
I know I have to use !, but I don't know exactly how and where, I have tried doing if y! % 4 == 0
, but that just seemed to make it worse.
I would also like to do the same thing for the method daysInMonth