Automatic plurals with inflect: true
Text("^[\(count) item](inflect: true)") picks "1 item" or "2 items" for you, with no if statements and no plural rules of your own.
iOS 15+macOS 12+ Swift 5.9
count == 1 ? "item" : "items" works in English and breaks the moment the app is translated. Foundation’s automatic grammar agreement handles it for you: mark the words that depend on a number, and the text is inflected to match.
import SwiftUI
struct BasketView: View {
@State private var count = 1
var body: some View {
Form {
Stepper(value: $count, in: 0...20) {
// "0 items", "1 item", "2 items"
Text("^[\(count) item](inflect: true) in your basket")
}
// Adjectives agree too: "1 new message", "3 new messages"
Text("You have ^[\(count) new message](inflect: true)")
}
}
}
#Preview {
BasketView()
}Outside SwiftUI, the same markup works with AttributedString:
let count = 3
let label = AttributedString(localized: "^[\(count) photo](inflect: true) selected")
print(String(label.characters)) // "3 photos selected"How it works
^[...](inflect: true)is Apple’s Markdown extension for attributes. In aTextstring literal, the whole string is aLocalizedStringKey, so the Markdown is parsed and the marked phrase is inflected when the string is localised.- The number inside the brackets drives the agreement: nouns and adjectives in the phrase change to match it.
- It works in the languages Foundation supports for automatic grammar agreement, including English, French, German, Italian, Portuguese and Spanish. Other languages show the text as written.
Gotchas
- It only works on a string literal or
LocalizedStringKey.Text(someString)with aStringvariable is shown verbatim, brackets and all. - Keep the number inside the brackets.
"\(count) ^[item](inflect: true)"has nothing to agree with. - For full control in every language, use a String Catalog in Xcode and choose Vary by Plural for the string instead. The catalog also picks up these inflected strings, so you can start with
inflect: trueand add plural variants later.