Write your own format style
Wrap your app's own formatting rules in a small struct and use them everywhere SwiftUI accepts a format, just like the built-in styles.
iOS 15+macOS 12+ Swift 5.9
Every app has values with house rules: a star rating, a flight code, a file version. Helper functions that return strings work, but they cannot be passed to Text or a text field. A custom format style can, and it reads exactly like the built-in ones at the call site.
import SwiftUI
struct StarRatingStyle: FormatStyle {
var maximum = 5
func format(_ value: Int) -> String {
let filled = min(max(value, 0), maximum)
return String(repeating: "★", count: filled)
+ String(repeating: "☆", count: maximum - filled)
}
}
extension FormatStyle where Self == StarRatingStyle {
static var stars: StarRatingStyle { StarRatingStyle() }
static func stars(outOf maximum: Int) -> StarRatingStyle {
StarRatingStyle(maximum: maximum)
}
}
struct ReviewRow: View {
let rating = 4
var body: some View {
VStack(alignment: .leading) {
Text(rating, format: .stars)
Text(rating, format: .stars(outOf: 10))
Text("Rated \(rating, format: .stars)")
}
.foregroundStyle(.orange)
}
}
#Preview {
ReviewRow()
}How it works
FormatStyleneeds one method,format(_:), plusCodableandHashable, which a struct of simple properties gets for free.- The input and output types come from the method signature: here
Intin andStringout, which is whatText(_:format:)needs. - A static property or function in an extension on
FormatStyle where Self == ...gives the leading-dot syntax, so.starssits alongside.numberand.currency. - Because it is a value, it can be stored, passed to other views and compared, unlike a closure.
Gotchas
- For a style that should follow the guest’s locale, add a
localeproperty and afunc locale(_ locale: Locale) -> Self. SwiftUI then hands it the environment’s locale. - To use the style in
TextField(_:value:format:), it must also conform toParseableFormatStyleand provide a parse strategy that turns text back into a value. - Keep the output plain text. Styling such as colours belongs in the view, so the same style works in
Text, accessibility labels and exported strings.