Today I Learned: Constrained Extension Methods in Swift

Brendan Thompson • 29 January 2023

Today I Learned you can have a constrained extension method on a Swift protocol. For instance, if you wanted to format a given string with the user's local currency settings we could do that by adding the following extension method to the FormatStyle protocol.

extension FormatStyle where Self == FloatingPointFormatStyle<Double>.Currency {
    static var localCurrency: Self {
        .currency(code: Locale.current.currency?.identifier ?? "USD")
    }
}

Then we would use that localCurrency styling on something in our View. This might look like this:

struct ContentView: View {
  @State private var amount = 0.0

  var body: some View {
    NavigationView {
      Form {
        TextField("Amount", value: $amount, format .localCurrency)
      }
    }
  }
}