enum conformance to RawRepresentable
"although I feel that conformance should be synthesized by the compiler"
Yes, here your rawValue
is of type String, not Int. Simply create your enum like:
enum WeekDay: String {
case monday, tuesday, wednesday, thursday, friday
}
And then create a WeekDay
like this:
let monday: WeekDay? = WeekDay(rawValue: "monday")
let notADay: WeekDay? = WeekDay(rawValue: "foo")
Of course you can also add a custom init which takes an integer as argument:
enum WeekDay: String {
case monday, tuesday, wednesday, thursday, friday
init?(integer: Int){
switch integer {
case 0 : self = .monday
case 1 : self = .tuesday
case 2 : self = .wednesday
case 3 : self = .thursday
case 4 : self = .friday
default : return nil
}
}
}
And create your weekDay like:
let monday: WeekDay? = WeekDay(integer: 0)
let notADay: WeekDay? = WeekDay(integer: 30)
Apparently your definition of init?(rawValue: Int)
prevents the compiler from inferring the RawValue
type automatically. Adding a type alias helps:
enum WeekDay: String {
typealias RawValue = String
case monday, tuesday, wednesday, thursday, friday
init?(rawValue: Int){
switch rawValue {
case 0 : self = .monday
case 1 : self = .tuesday
case 2 : self = .wednesday
case 3 : self = .thursday
case 4 : self = .friday
default : return nil
}
}
}
Alternatively define your custom init function with a different parameter name:
enum WeekDay: String {
case monday, tuesday, wednesday, thursday, friday
init?(rawInt: Int){
switch rawInt {
case 0 : self = .monday
case 1 : self = .tuesday
case 2 : self = .wednesday
case 3 : self = .thursday
case 4 : self = .friday
default : return nil
}
}
}
As of Swift 5 there is no error of having a second init?(rawValue: Int)
in addition to synthesized init?(rawValue: String)
. But if you want to override that RawRepresantable
implementation and have rawValue
be Int
, it is possible.
extension WeekDay : RawRepresentable {
typealias RawValue = Int
init?(rawValue: Int){
switch rawValue {
case 0 : self = .monday
case 1 : self = .tuesday
case 2 : self = .wednesday
case 3 : self = .thursday
case 4 : self = .friday
default : return nil
}
}
var rawValue: Int {
switch self {
case .monday : return 0
case .tuesday : return 1
case .wednesday : return 2
case .thursday : return 3
case .friday : return 4
}
}
}
print(WeekDay.init(rawValue: 2)) // Optional(WeekDay.wednesday)
print(WeekDay.RawValue.self) // Int