noloman
noloman

Reputation: 11975

SwiftUI enum with custom rawValue

I'm querying an API and I'm retrieving some values that I code into JSON. One of the attributes is job_type whose value I know that could only take some finite range of values, so I've written:

enum JobType: String, Codable {
  case contract = "contract"
  case empty = ""
  case freelance = "freelance"
  case fullTime = "full_time"
  case other = "other"
  case partTime = "part_time"
}

What I want to do is, in SwiftUI, have a Text that shows for example Full time instead of the JSON attribute which would be full_time, of Part time instead of part_time. How can I do this?

EDIT: I have tried Text(job.job_type) an I'm getting an error: Initializer 'init(_:)' requires that 'Jobs.JobType' conform to 'StringProtocol'. Did you mean to use '.rawValue'?

Thanks in advance!

Upvotes: 1

Views: 300

Answers (2)

you could do something crude and simple like this:

enum JobType: String, Codable {
  case contract = "contract"
  case empty = ""
  case freelance = "freelance"
  case fullTime = "full_time"
  case other = "other"
  case partTime = "part_time"
    
    func asString() -> String {
        switch self {
        case .contract: return "Contract"
        case .empty: return ""
        case .freelance: return "Freelance"
        case .fullTime: return "Full time"
        case .other: return "Other"
        case .partTime: return "Part time"
        }
    }
}
    

and use it like this:

Text(job.job_type.asString())

Upvotes: 1

Joakim Danielson
Joakim Danielson

Reputation: 51973

Add the following computed property to your enum

var displayText: String {
    self.rawValue.replacingOccurrences(of: "_", with: " ").capitalized
}

and call it like

Text(job.job_type.displayText)

Upvotes: 1

Related Questions