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.

StarRatingStyle.swift
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

Gotchas

See also