Momen Abdelkarim Momen Abdelkarim - 3 months ago 21
Swift Question

"Cannot force unwrap value of non-optional type 'Int'" error?

func decideLeapYear(year: Int) -> Bool{
var lyear: Bool = false
if(year<1582){
if(((year/4)%1)==0){
lyear = true
}
}
else if(year>=1582)
{
if(((year%4)==0) || (year%400==0) && ((year%100)!=0)){
lyear = true
}
}

return lyear
}


At the end of the
if
statement in the
else if
statement, Xcode throws this error:


Cannot force unwrap value of non-optional type 'Int'


when it reaches the statement:

((year%100)!=0))


Can anyone explain why and how I can fix this?

Answer

This is because the compiler thinks that ((year%100)!=0)) is actually ((year%100)! = 0)) and so tries to unwrap (year%100)!.

The solution is to add a space before !=:

func decideLeapYear(year: Int) -> Bool{
    var lyear: Bool = false
    if(year<1582){
        if(((year/4)%1)==0){
            lyear = true
        }
    }

    else if(year>=1582)
    {
        if(((year%4)==0) || (year%400==0) && ((year%100) != 0)) {
            lyear = true
        }
    }

    return lyear
}

Also, just a note: you don't need to enclose conditions in brackets, and space characters in code don't cost anything. So I suggest adding some air to your code like this:

func decideLeapYear(year: Int) -> Bool {
    if year < 1582 {
        if (year / 4) % 1 == 0 {
            return true
        }
    } else if year >= 1582 {
        if year % 4 == 0 || year % 400 == 0 && year % 100 != 0 {
            return true
        }
    }
    return false
}

I've also removed the bool variable to make the code even cleaner.