Kesey
March 21, 2021, 9:38pm
1
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
1 Like
ibex10
March 21, 2021, 11:26pm
2
// 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)")
Kesey
March 22, 2021, 6:17pm
3
Fancy operator @ibex10 . Not quite sure you followed the directions though
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.
// silver challenge
extension Int {
enum Parity {
case even, odd
}
var parity: Parity {
if self % 2 == 0 {
return .even
} else {
return .odd
}
}
}
let twelve = 12
print(twelve.parity) // even
// twelve.parity = .odd // should generate an error because parity is read-only
let eleven = 11
print(eleven.parity) // odd
2 Likes