swift - Can you extend an enum? -
i use enums store string values this:
enum animals: string { case desccat = "i has attitude" case descdog = "how can help" case descgator = "i eat you" var s: string { { return self.rawvalue string } } } then access them this:
print("dogs like:" + animals.descdog.s) my question can extend enums other struct or object don't have add var s: string {} property each enum?
you want add property enums raw value string? sounds case constrained protocol extensions!
extension rawrepresentable rawvalue == string { var description: string { return rawvalue } } this works because enums raw value automatically conform rawrepresentable protocol, , said protocol has associated type rawvalue tells type raw value is.
now animals enum automatically inherit it:
print(animals.desccat.description) // -> "i has attitude" notice string enums customstringconvertible, have description property (that returns name of enum case), , yours doesn't override it:
print(animals.desccat) // -> "desccat" if want description override default, add declaration of customstringconvertible conformance enum:
private enum animals: string, customstringconvertible { /*...*/ } print(animals.desccat) // -> "i has attitude" you can extend idea cover other raw value types. example:
extension rawrepresentable rawvalue: customstringconvertible { var description: string { return rawvalue.description } } now, can automatic descriptions enums raw value int or custom type (so long type has description of own).
Comments
Post a Comment