Skip to content

Instantly share code, notes, and snippets.

@ole
Created July 19, 2023 08:36
Show Gist options
  • Save ole/4965ed012a7fe4dc902b0ea913a1ab46 to your computer and use it in GitHub Desktop.
Save ole/4965ed012a7fe4dc902b0ea913a1ab46 to your computer and use it in GitHub Desktop.
Generic ordinal format style for all BinaryInteger types
import Foundation
extension FormatStyle {
static func ordinal<FormatInput: BinaryInteger>() -> OrdinalFormatStyle<FormatInput>
where Self == OrdinalFormatStyle<FormatInput>
{
OrdinalFormatStyle()
}
}
struct OrdinalFormatStyle<FormatInput: BinaryInteger>: FormatStyle {
func format(_ value: FormatInput) -> String {
let formatter = NumberFormatter()
formatter.numberStyle = .ordinal
return formatter.string(for: value)!
}
}
(42 as Int).formatted(.ordinal()) // "42nd"
(42 as UInt8).formatted(.ordinal()) // "42nd"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment