objective-carraysstringcocoahuman-readable

Create a comma-separated list with "and" before the last item in Objective-C, in particular


I want to write a method that provides a human-readable string representation of arrays, with comma-spaces when necessary (incl. the Oxford Comma), and a conjoining " and " at the end.

For example, say I have these arrays:

NSArray *nun = @[];
NSArray *won = @[@"The Loneliest"];
NSArray *too = @[@"Peas", @"Pod"];
NSArray *tree = @[@"Apple", @"Falls", @"Far, Far Away"];

I want to write a method like:

+ (NSString*) humanReadableListFromArray: (NSArray*) arr
{
  // magic
}

And when I pass my arrays through, I want them to look like this:

@""
@"The Loneliest"
@"Peas and Pod"
@"Apple, Falls, and Far, Far Away"

Note that the first one, having exactly 1 item, is just the first item without decoration. The second, having exactly 2 items, has no commas, but does have the conjoining " and ". The third, having more than 2 items, includes a comma-space between each item, and the last item includes an additional and just after the comma-space and before the item.

Is there a short way to do this in Objective C? I've done this in languages like Java, but I know that Objective C features methods like -(NSString*)[NSArray componentsJoinedByString:] that might assist in this.


This question is not answered by Replace last comma in string with an "and". (Objective-C) because it does not address commas in the last array item. I've also looked into questions like Objective-C Simplest way to create comma separated string from an array of objects, and they don't mention this nice part of human readability.


Solution

  • As of iOS 13, there is now built-in support for this: (NS)ListFormatter, which is even better than the other answers listed here, because it handles localization.