Skip to content

Instantly share code, notes, and snippets.

@seanwoodward
Last active November 4, 2023 22:53
Show Gist options
  • Save seanwoodward/d6ace5003d1976dc0b8dba78f4a32c57 to your computer and use it in GitHub Desktop.
Save seanwoodward/d6ace5003d1976dc0b8dba78f4a32c57 to your computer and use it in GitHub Desktop.
Quick and dirty FormatStyle for ordinal representation of a given Int
struct OrdinalNumberFormatStyle: FormatStyle {
func format(_ value: Int) -> String {
Self.ordinalFormatter.string(from: NSNumber(value: value)) ?? String(describing: value)
}
static var ordinalFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .ordinal
formatter.locale = .autoupdatingCurrent
return formatter
}()
}
extension FormatStyle where FormatInput == Int, FormatOutput == String, Self == OrdinalNumberFormatStyle {
static var ordinal: OrdinalNumberFormatStyle {
OrdinalNumberFormatStyle()
}
}
struct NumberView: View {
@State var number: Int
var body: some View {
Text("\(number.formatted(.ordinal))")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment