0

I have a simple enum of type string:

enum MyEnum: String {
    case hello = "hello"
    case world = "world"
}

And I want to write a case-insensitive constructor. I tried this (with or without extension):

init?(string: String) {
    return self.init(rawValue: string.lowercased())
}

but I get an error saying:

'nil' is the only value permitted in an initializer

1 Answer 1

3

You don't need to return anything. You just call initializer:

enum MyEnum: String {
    case hello = "hello"
    case world = "world"

    init?(caseInsensitive string: String) {
        self.init(rawValue: string.lowercased())
    }
}

print(MyEnum(caseInsensitive: "HELLO") as Any) // => Optional(Untitled.MyEnum.hello)
print(MyEnum(caseInsensitive: "Goodbye") as Any) // => nil
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.