What is the easiest and best way in Objective-C to combine a list (NSArray) of NSStrings into a single NSString separated by commas, with the grammatically correct terminal conjunction “, and ” before the final item of the list?
NSArray *anArray = [NSArray arrayWithObjects:@"milk", @"butter", @"eggs", @"spam", nil];
From this array, I want the NSString @"milk, butter, eggs, and spam".
More generally, if the list is more than two items long, I want ", " between every item except the last and second-to-last (which should have ", and "). If the list is two items long, I want just the ' and ' with no comma. If the list is one item long, I want the single string from the array.
I like something as simple as:
NSString *newString = [anArray componentsJoinedByString:@", "];
But this of course omits the ‘and’ conjunction.
Is there a simpler and/or faster Objective-C way than the following:
- (NSString *)grammaticallyCorrectStringFromArrayOfStrings:(NSArray *)anArray {
if (anArray == nil) return nil;
int arrayCount = [anArray count];
if (arrayCount == 0) return @"";
if (arrayCount == 1) return [anArray objectAtIndex:0];
if (arrayCount == 2) return [anArray componentsJoinedByString:@" and "];
// arrayCount > 2
NSString *newString = @"";
for (NSString *thisString in anArray) {
if (thisString != [anArray objectAtIndex:0] && thisString != [anArray lastObject]) {
newString = [newString stringByAppendingString:@", "];
}
else if (thisString == [anArray lastObject]) {
newString = [newString stringByAppendingString:@", and "];
}
newString = [newString stringByAppendingString:thisString];
}
return newString;
}
For the loop, I’d probably do something like
Though I guess that’s not really less lines.