Using Plurals in Swift

Your Swift code determines how strings are extracted into .xcstrings files. Here's how to write code that supports pluralization.

SwiftUI#

The simplest way to create plural strings:

Text("\(count) items")

Xcode automatically detects this needs plural handling and creates variations in your String Catalog.

Automatic Grammar Agreement#

Swift's inflection engine handles plurals intelligently:

Text("^[\(count) item](inflect: true)")

This works for English and many other languages.

With Comments#

Add context for translators:

Text("\(count) items",
     comment: "Shopping cart item count, shown in tab badge")

Foundation#

For non-UI strings:

let message = String(localized: "\(count) files selected",
                     comment: "Status bar showing selection count")

Best Practices#

Keep the number in the string#

// Good: number is part of the string
Text("\(count) items")

// Bad: won't pluralize correctly
HStack {
    Text("\(count)")
    Text("items")
}

Don't concatenate localized strings#

// Bad: broken pluralization
let text = "\(count) " + String(localized: "items")

// Good: single localized string
let text = String(localized: "\(count) items")

Format Specifiers#

When Xcode extracts plural strings, it uses format specifiers:

Swift TypeFormat Specifier
Int%lld
Double%lf
String%@
Text("\(count) items")
// Becomes: "%lld items" in the xcstrings file

Example#

struct CartView: View {
    let itemCount: Int

    var body: some View {
        VStack {
            Text("\(itemCount) items in your cart")
            Text("^[\(itemCount) item](inflect: true) ready")
        }
    }
}

The String Catalog will contain plural variations for these strings that you can translate to any language.