Well, as colon is kind of special symbol, but is part of method signature, it is possible to exted the NSString
with category to add this non-idiomatic style of string concatenation:
[@"This " : @"feels " : @"almost like " : @"concatenation with operators"];
You can define as many colon separated arguments as you find useful... ;-)
For a good measure, I've also added concat:
with variable arguments that takes nil
terminated list of strings.
// NSString+Concatenation.h
#import <Foundation/Foundation.h>
@interface NSString (Concatenation)
- (NSString *):(NSString *)a;
- (NSString *):(NSString *)a :(NSString *)b;
- (NSString *):(NSString *)a :(NSString *)b :(NSString *)c;
- (NSString *):(NSString *)a :(NSString *)b :(NSString *)c :(NSString *)d;
- (NSString *)concat:(NSString *)strings, ...;
@end
// NSString+Concatenation.m
#import "NSString+Concatenation.h"
@implementation NSString (Concatenation)
- (NSString *):(NSString *)a { return [self stringByAppendingString:a];}
- (NSString *):(NSString *)a :(NSString *)b { return [[self:a]:b];}
- (NSString *):(NSString *)a :(NSString *)b :(NSString *)c
{ return [[[self:a]:b]:c]; }
- (NSString *):(NSString *)a :(NSString *)b :(NSString *)c :(NSString *)d
{ return [[[[self:a]:b]:c]:d];}
- (NSString *)concat:(NSString *)strings, ...
{
va_list args;
va_start(args, strings);
NSString *s;
NSString *con = [self stringByAppendingString:strings];
while((s = va_arg(args, NSString *)))
con = [con stringByAppendingString:s];
va_end(args);
return con;
}
@end
// NSString+ConcatenationTest.h
#import <SenTestingKit/SenTestingKit.h>
#import "NSString+Concatenation.h"
@interface NSString_ConcatenationTest : SenTestCase
@end
// NSString+ConcatenationTest.m
#import "NSString+ConcatenationTest.h"
@implementation NSString_ConcatenationTest
- (void)testSimpleConcatenation
{
STAssertEqualObjects([@"a":@"b"], @"ab", nil);
STAssertEqualObjects([@"a":@"b":@"c"], @"abc", nil);
STAssertEqualObjects([@"a":@"b":@"c":@"d"], @"abcd", nil);
STAssertEqualObjects([@"a":@"b":@"c":@"d":@"e"], @"abcde", nil);
STAssertEqualObjects([@"this " : @"is " : @"string " : @"concatenation"],
@"this is string concatenation", nil);
}
- (void)testVarArgConcatenation
{
NSString *concatenation = [@"a" concat:@"b", nil];
STAssertEqualObjects(concatenation, @"ab", nil);
concatenation = [concatenation concat:@"c", @"d", concatenation, nil];
STAssertEqualObjects(concatenation, @"abcdab", nil);
}