Skip to content

Instantly share code, notes, and snippets.

@beccadax
Created August 9, 2013 01:04
Show Gist options
  • Save beccadax/6190337 to your computer and use it in GitHub Desktop.
Save beccadax/6190337 to your computer and use it in GitHub Desktop.
Category to turn @[ @"a", @"b", @"c" ] into @"a, b and c". So useful I must have it in three different apps.
//
// NSArray+Conjunction.h
// Typesetter
//
// Created by Brent Royal-Gordon on 2/11/12.
// Copyright (c) 2012 Architechies. All rights reserved.
//
@interface NSArray (Conjunction)
@property (readonly) NSString * conjunction;
@end
@interface NSSet (Conjunction)
@property (readonly) NSString * conjunction;
@end
//
// NSArray+Conjunction.m
// Typesetter
//
// Created by Brent Royal-Gordon on 2/11/12.
// Copyright (c) 2012 Architechies. All rights reserved.
//
#import "NSArray+Conjunction.h"
@implementation NSArray (Conjunction)
- (NSString *)conjunction {
BOOL last = YES;
NSString * accumulator;
for(NSString * item in self.reverseObjectEnumerator) {
if(!accumulator) {
accumulator = item;
}
else if(last) {
accumulator = [NSString stringWithFormat:@"%@ and %@", item, accumulator];
last = NO;
}
else {
accumulator = [NSString stringWithFormat:@"%@, %@", item, accumulator];
}
}
return accumulator;
}
@end
@implementation NSSet (Conjunction)
- (NSString *)conjunction {
NSArray * array = [self.allObjects sortedArrayUsingSelector:@selector(localizedStandardCompare:)];
return array.conjunction;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment