swiftlang / swift

The Swift Programming Language
https://swift.org
Apache License 2.0
67.33k stars 10.34k forks source link

CaseIterable RawRepresentable enum: when using index in allCases as raw representation, rawValue property gets stuck in infinite loop. #68866

Open kr1sc opened 11 months ago

kr1sc commented 11 months ago

Description

Below code does not work.

enum TestEnum: CaseIterable {
    case one, two, three
}

extension TestEnum: RawRepresentable {

    init?(rawValue: Int) {
        guard rawValue >= 0 && rawValue < TestEnum.allCases.count else { return nil }
        self = TestEnum.allCases[rawValue]
    }

    var rawValue: Int {
        TestEnum.allCases.firstIndex(of: self)!
    }

}

TestEnum.one.rawValue

TestEnum.one.rawValue will cause recursive cascade of rawValue invocations resulting in EXC_BAD_ACCESS. For me it looks like invalid behavior.

Steps to reproduce

Run above code.

Expected behavior

TestEnum.one.rawValue correctly evaluates to value 0 in this case.

Screenshot 2023-09-29 at 18 23 36

Environment

aniket-singh-01 commented 11 months ago

Hi,kr1sc.
Can I take the issue?.

kr1sc commented 11 months ago

Hi Aniket, I just report what I suspect is incorrect behavior, but I do not decide how it is handled or by whom.