Is there a way to provide rawValue strings as sentence case (first letter in uppercase)

Hi,

Is there a way to generate / provide as sentence case (first letter in uppercase) raw value strings to enum cases with camelcase.

enum Category: String {
    case employeeList // = "EmployeeList"
    case markSheet // = "MarkSheet"
}

Note: I like the case to be in camel case while only the rawString to be in sentence case

Questions:

  1. Is there any way Swift / Xcode tricks can populate this?
  2. Is there a better approach? (this seems a use case that I seem to want)

I don't think there is a way to influence the compiler-generated RawRepresentable conformance, but depending on your use case, you may be able to deal with this at some other layer.

I have e.g. some JSON-data that I want to decode from Pascal casing, so I use the compiler generated raw values, and computer generated coding keys, and use a key decoding strategy to convert the keys while decoding:

extension JSONDecoder.KeyDecodingStrategy {
    static let convertFromPascalCase = custom { keyPath in
        struct AnyKey: CodingKey {
            var stringValue: String
            var intValue: Int?
            init?(stringValue: String) { self.stringValue = stringValue }
            init?(intValue: Int) { self.stringValue = ""; self.intValue = intValue }
        }
        let upperCasedKey = keyPath.last!.stringValue
        return AnyKey(stringValue: upperCasedKey.first!.lowercased() + upperCasedKey.dropFirst())!
    }
}

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromPascalCase

let data = Data(...)
let model = try decoder.decode(MyModel.self, from: data)
2 Likes

Thanks a lot @sveinhal for clarifying that there is no straight forward way.

I am not doing any coding / decoding, was using it in logs

I will just hardcode those values with the case that I prefer.