好吧,由于冒号是一种特殊符号,但它是方法签名的一部分,因此可以扩展NSString
with 类别以添加这种非惯用的字符串连接样式:
[@"This " : @"feels " : @"almost like " : @"concatenation with operators"];
您可以定义尽可能多的冒号分隔的参数,只要您觉得有用... ;-)
作为一个很好的衡量标准,我还添加concat:
了可变参数,这些参数采用nil
终止的字符串列表。
// 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);
}