How to make text plural?

57 views Asked by At

I want the text "Max Attendee" to be plural when CurrentContacts is not equal to 1. The code below is not working:

Text("^[Max Attendee \(currentContacts)](inflect: true)")

Expected results:

Max Attendees 0
Max Attendee 1
Max Attendees 2
Max Attendees 3
2

There are 2 answers

0
Sweeper On BEST ANSWER

This is simply because this is not how people usually speak English, so the inflection engine behaves weirdly. See also this post on ELU.SE.

When you want "Max Attendees" to come first, you should always use plural, and also add a colon in between. "Max Attendees: 1" is fine. "Max Attendee 1" is weird.

It is when the noun comes after the number, do we inflect. "Max 1 Attendee", "Max 2 Attendees", etc.

Compared the outputs of

Text("^[Max Attendees \(n)](inflect: true)")

and

Text("^[Max \(n) Attendees](inflect: true)")

The former results in "Attendees" for every number, and the latter results in "Max Attendee" for 1, and "Max Attendees" for everything else.

If you really want to put "Max Attendee" first and also inflect, add explicit localisation keys for the singular/plural forms in your string catalog. That is, use

Text("Max Attendees \(i)")

Right-click on the string catalog key, and click "Vary by plural". Then you can write whatever text you want in each case:

enter image description here

0
J W On

Their is a very easy way to do this. o(^v^)o

You can use Bool ? String : String to judge is it an odd number (the number is 1).

Which currentContacts == 1 ? "Max Attendee" : "Max Attendees"

Example: Example picture

Code:

import SwiftUI

struct ContentView: View {
  var body: some View {
    VStack {
      ForEach(0..<6, id: \.self) { currentContacts in
        let attendeeText = currentContacts == 1 ? "Max Attendee" : "Max Attendees"
        
        Text("\(attendeeText) \(currentContacts)")
      }
    }
  }
}

#Preview {
  ContentView()
}