具有自定义 rawValue 的 SwiftUI 枚举
SwiftUI enum with custom rawValue
我正在查询 API 并且正在检索一些我编码到 JSON 中的值。
其中一个属性是 job_type
,我知道它的值只能取一些有限范围的值,所以我写了:
enum JobType: String, Codable {
case contract = "contract"
case empty = ""
case freelance = "freelance"
case fullTime = "full_time"
case other = "other"
case partTime = "part_time"
}
我想要做的是,在 SwiftUI 中,有一个 Text
显示例如 Full time
而不是 JSON 属性,它是 full_time
, Part time
而不是 part_time
。我该怎么做?
编辑:我已尝试 Text(job.job_type)
,但出现错误:
Initializer 'init(_:)' requires that 'Jobs.JobType' conform to 'StringProtocol'. Did you mean to use '.rawValue'?
提前致谢!
你可以像这样粗略地做一些事情:
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"
}
}
}
并像这样使用它:
Text(job.job_type.asString())
将以下计算 属性 添加到您的枚举中
var displayText: String {
self.rawValue.replacingOccurrences(of: "_", with: " ").capitalized
}
并这样称呼它
Text(job.job_type.displayText)
我正在查询 API 并且正在检索一些我编码到 JSON 中的值。
其中一个属性是 job_type
,我知道它的值只能取一些有限范围的值,所以我写了:
enum JobType: String, Codable {
case contract = "contract"
case empty = ""
case freelance = "freelance"
case fullTime = "full_time"
case other = "other"
case partTime = "part_time"
}
我想要做的是,在 SwiftUI 中,有一个 Text
显示例如 Full time
而不是 JSON 属性,它是 full_time
, Part time
而不是 part_time
。我该怎么做?
编辑:我已尝试 Text(job.job_type)
,但出现错误:
Initializer 'init(_:)' requires that 'Jobs.JobType' conform to 'StringProtocol'. Did you mean to use '.rawValue'?
提前致谢!
你可以像这样粗略地做一些事情:
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"
}
}
}
并像这样使用它:
Text(job.job_type.asString())
将以下计算 属性 添加到您的枚举中
var displayText: String {
self.rawValue.replacingOccurrences(of: "_", with: " ").capitalized
}
并这样称呼它
Text(job.job_type.displayText)