Chapter 20: Extensions / Silver Challenge

Curious to see other solutions. Here’s mine…

extension Int {
   var remainder: Int { return self % 2}
}

extension Int {
    enum EvenOdd {
        case even, odd
    }
    
    var evenodd: EvenOdd {
        switch remainder {
        case 0:
            return .even
        default:
            return .odd
        }
    }
}

var someNumber: Int

someNumber = 2
someNumber.remainder //0
someNumber.evenodd //even

someNumber = 27
someNumber.remainder //1
someNumber.evenodd //odd
// Using the bitwise AND operator
extension Int {
    var isOdd : Bool {
        return (self & 1) == 1
    }
    
    var isEven : Bool {
        return !isOdd
    }
}

print ("\(2) is odd:  \(2.isOdd)")
print ("\(3) is odd:  \(3.isOdd)")
print ("\(2) is even: \(2.isEven)")
print ("\(3) is even: \(3.isEven)")

Fancy operator @ibex10. Not quite sure you followed the directions though :wink:

Give the Int type a nested enum with cases even and odd. Also give Int a property of that type to correctly report whether an integer is even or odd.