1

I'd like to append an s to the end of a string, if the value of a variable is > 1.

There are obviously several ways to accomplish this - for example:

if(points == 1) {
     points_as_string = "1 Point"
} else {
     points_as_string = "\(points) Points"
}

A shorter version could be:

points_as_string = (points == 1 ? "1 Point" : "\(points) Points")

An even shorter version would be:

points_as_string = "\(points) Point" + (points == 1 ? "" : "s")

Is it possible to write something even shorter than that, or is that as good as it gets?

Cristik
  • 30,989
  • 25
  • 91
  • 127
Ben
  • 4,707
  • 5
  • 34
  • 55
  • For proper pluralization in multiple languages you would use NSLocalizedString and .stringsdict files, see https://developer.apple.com/library/ios/documentation/MacOSX/Conceptual/BPInternational/LocalizingYourApp/LocalizingYourApp.html#//apple_ref/doc/uid/10000171i-CH5-SW10. A simple example is here: http://stackoverflow.com/questions/25862960/ios-swift-and-localizedstringwithformat. – Martin R Jan 05 '16 at 20:18

2 Answers2

3

Only very slightly shorter:

points_as_string = "\(points) Point\(points == 1 ? "" : "s")"
rob mayoff
  • 375,296
  • 67
  • 796
  • 848
3

Here is a shorter version that uses a dictionary lookup and the nil coalescing operator ??:

points_as_string = "\(points) Point\([1:""][points] ?? "s")"
vacawama
  • 150,663
  • 30
  • 266
  • 294