Created
July 19, 2023 08:36
-
-
Save ole/4965ed012a7fe4dc902b0ea913a1ab46 to your computer and use it in GitHub Desktop.
Generic ordinal format style for all BinaryInteger types
This file contains 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
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