Last active
November 4, 2023 22:53
-
-
Save seanwoodward/d6ace5003d1976dc0b8dba78f4a32c57 to your computer and use it in GitHub Desktop.
Quick and dirty FormatStyle for ordinal representation of a given Int
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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