I was playing with CustomStringConvertible for my enum in XCode playground and I encountered a really strange problem.

See following enum:

enum A {
    case v(UInt8)

    init(val: UInt8) {
        self = .v(val)
    }
}

var a = A(val: 5)
print("\(a)")

This code works without any problem and a will be equal to .v(5).

After that, I tried to make this class conform to CustomStringConvertible. So, I implemented description calculated property:

enum A {
    case v(UInt8)

    init(val: UInt8) {
        self = .v(val)
    }

    var description: String {
        return "\(self)"
    }
}

var a = A(val: 5)
print("\(a) \(a.description)")

and still everything works as expected. Then I just added protocol conformance in declaration:

enum A: CustomStringConvertible {
    case v(UInt8)

    init(val: UInt8) {
        self = .v(val)
    }

    var description: String {
        return "\(self)"
    }
}

var a = A(val: 5)
print("\(a) \(a.description)")

Strangely, Now I get segmentation fault. Even though I'm a beginner in swift I find this problem funny and I have never seen that protocol conformace declaration can cause this problem.

Any idea why this happens?

1 Answers

1
Martin R On Best Solutions

String interpolation (as in "\(self)") calls the description property for values of types which conform to the CustomStringConvertible protocol.

Which means that your implementation of var description calls itself recursively, which eventually causes a stack overflow and termination of the program.