我想使用一个枚举将整数转换为工作日的字符串名称。我提出了以下建议
// Enum to output days
enum EnumDays : Int
{
case MONDAY = 0
case TUESDAY
case WEDNESDAY
case THURSDAY
case FRIDAY
case SATURDAY
case SUNDAY
}
var weekDay = EnumDays.init(rawValue: 0)
print("Day = \(String(describing: weekDay))")
但是我们输出的类型如
“ Day = Optional(SubscriptInSwift.EnumDays.MONDAY)”
如何生成字符串形式的输出,即:
“天=星期一”
这个问题是我一段时间以来遇到的问题的最低限度的示例,尽管此示例是关于工作日的,但我正在寻找一种解决方案,该方法通常将Integers转换为String。
答案 0 :(得分:2)
enum EnumDays: Int, CustomStringConvertible
{
var description: String {
switch self {
case .MONDAY:
return "Monday"
case .TUESDAY:
return "Tuesday"
case .WEDNESDAY:
return "Wednesday"
case .THURSDAY:
return "Thursday"
case .FRIDAY:
return "Friday"
case .SATURDAY:
return "Saturday"
case .SUNDAY:
return "Sunday"
}
}
case MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY,SUNDAY
}
并使用if来解开枚举对象
if let weekDay = EnumDays.init(rawValue: 0) {
print("Day = \(weekDay)")
}
您可以从Calendar.current.weekdaySymbols
print(Calendar.current.weekdaySymbols)//["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
print(Calendar.current.shortWeekdaySymbols)//["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
答案 1 :(得分:1)
您只需解开weekDay
print("Day = \(String(describing: weekDay!))")
答案 2 :(得分:1)
这是我使用的另一种允许本地化的模式。我将使用您的日历示例。为每个值使用一个显式值可以使您使用带空格或其他标点符号的短语,然后意味着如果需要其他语言,则可以轻松地使用本地化。您可以使用额外的代码来支付优雅的费用-您可以决定是否值得。
enum DaysOfWeek : Int
{
case MONDAY = 0
case TUESDAY
case WEDNESDAY
case THURSDAY
case FRIDAY
case SATURDAY
case SUNDAY
var asString : String
{
var resource = ""
switch self
{
case .MONDAY: resource = "Monday"
case .TUESDAY : resource = "Tuesday"
case .WEDNESDAY: resource = "Wednesday"
...
}
// Use Internationalization, as appropriate.
return NSLocalizedString(resource, comment: resource)
}
}