to provide some additional context to my original post...
Here is another enum for which I can access a raw value for an enum, but it is not pure - it has an associated type NSNumber.
The significant difference to this enum is that is has an associated type NSNumber and so I can set a typealias RawValue = NSNumber.
enum EntityDateFormat: NSNumber, CaseIterable, Identifiable {
typealias RawValue = NSNumber
var id: NSNumber? { self.rawValue }
case dateTime = 0
case dateOnly
case monthYear
case yearOnly
var template: String {
switch self {
case .dateTime: return Date.templateDDMYHM
// e.g. under extension to Date, static let templateDDMYHM: String! = "EEE dd MMM yyyy hh mm"
case .dateOnly: return Date.templateDDMY
case .monthYear: return Date.templateMY
case .yearOnly: return Date.templateY
}
}
var calendarComponent: Calendar.Component {
switch self {
case .dateTime: return .minute
case .dateOnly: return .day
case .monthYear: return .month
case .yearOnly: return .year
}
}
var title: String {
switch self {
case .dateTime: return "Date & Time"
case .dateOnly: return "Date Only"
case .monthYear: return "Month & Year"
case .yearOnly: return "Year Only"
}
}
var prefix: String {
switch self {
case .dateTime: return "At"
case .dateOnly: return "On"
case .monthYear: return "In"
case .yearOnly: return "In"
}
}
}
Then I use a function to obtain a formatted string, but I use a parameter format of type NSNumber to reference against the enum and obtain a raw value.
struct EntityDate {
private let messageError: String = "Error formatting EntityDate"
func from(_ date: Date, withFormat format: NSNumber) -> String {
guard
let calendarComponent = EntityDateFormat(rawValue: format)?.calendarComponent,
let template = EntityDateFormat(rawValue: format)?.template,
let prefix = EntityDateFormat(rawValue: format)?.prefix
else {
return messageError
}
let dateRounded = date.roundDown(to: calendarComponent)
let dateFormatted = dateRounded.formatAsStringUsing(template: template, forLocale: Locale.current)
return String("\(prefix) \(dateFormatted)")
}
Where .roundDown(to:) and formatAsStringUsing(template:, forLocale:) are custom functions under an extension to Date.
So as you can see in this last func, rather than having to run the value for the parameter format through a switch statement to obtain the relevant enum value, (using EntityDateFormat(rawValue: format)?) I have three single lines in a guard statement to determine each value I require for my custom Date functions.