I have enums that I use to define what values specific properties on my models can have (without having those strings littered throughout the code). Since the models are stored in realm, they can't be of this enum type but are strings instead.
An enum would look like this:
public enum SomeType: String {
case one
case two
case three
}
Currently I do the comparison like this:
model.field == SomeType.one.rawvalue
While this does work, I would prefer to not have to add the raw value every time. So instead I would like to be able to write this:
model.field == SomeType.one
With this, swift complains that it can not use the operator == on the type String and SomeType. I already tried adding a custom operator on the SomeType enum, that allows a comparison with String, however swift does not seem to actually use this and still gives the same error. Is it possible to achieve what I want or does swift forbid it for some reason?
Use operator overload:
public enum SomeType: String {
case one = "1"
case two = "2"
case three = "3"
}
public func ==(left: SomeType, right: String) -> Bool {
return left.rawValue == right
}
public func ==(left: String, right: SomeType) -> Bool {
return right == left.rawValue
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With