1

I'm trying to modify description output for ErrorProtocol. But this snippet, gives me infinite loop.

enum GeneralError: ErrorProtocol, CustomStringConvertible {
      case NoMemory

      var description: String {
          return String(self).lowercased()
      }
 }

Changing to self.dynamic type gives me a "generalerror".

Is there any way how to get just "nomemory"? Without using conditionals.

pravdomil
  • 2,961
  • 1
  • 24
  • 38

2 Answers2

4

Swift: Convert enum value to String? isn't an exact match for your question, but it really covers the guts of it. In your case, you'll want to change it up a little bit:

enum Error : String, ErrorProtocol, CustomStringConvertible {
    case NoMemory

    var description : String {
        return self.rawValue.lowercaseString
    }
}

This works because the default rawValue for enum cases where the associated type is String is the name of the case.

Community
  • 1
  • 1
David Berry
  • 40,941
  • 12
  • 84
  • 95
0

When you call String(self) in GeneralError.description, you're making the String initializer use your object (self) as a CustomStringConvertible to make a new string. Internally, it does this by calling description on it, hence the recursion

What exactly are you trying to achieve?

Alexander
  • 59,041
  • 12
  • 98
  • 151