Swift 可变参数& Objective-C 可变参数
2016-12-12 本文已影响291人
WonderChang
Objective-C中可变参数的API很多,如:
void NSLog(NSString *format, ...)
+ (instancetype)stringWithFormat:(NSString *)format, ...
- (instancetype)initWithTitle:(nullable NSString *)title message:(nullable NSString *)message delegate:(nullable id /*<UIAlertViewDelegate>*/)delegate cancelButtonTitle:(nullable NSString *)cancelButtonTitle otherButtonTitles:(nullable NSString *)otherButtonTitles, ...
像以上方法中的最后一个参数, ...
如何实现实现呢?如下:
- (NSString *)appendString:(NSString *)string otherSting:(NSString *)aString, ... {
//重点在以下,这里我们定义一个数组来承载可变参数,最后做拼装
NSMutableArray *arr = [[NSMutableArray alloc] init];
//定义一个指向个数可变的参数列表指针
va_list params;
id argument;
if (aString) {
[arr addObject:aString];
va_start(params, aString);
//返回参数列表中指针所指的参数,第二个参数为返回类型,并使指针指向参数列表中下一个参数
while ((argument = va_arg(params, id))) {
[arr addObject:argument];
}
//释放列表指针
va_end(params);
}
return [NSString stringWithFormat:@"%@ %@", string, [arr componentsJoinedByString:@" "]];
}
调用时注意参数最后一个需要传nil,如下:
[xxx appendString:@"hello" otherSting:@"I", @"am", @"a", @"good", @"man", nil]
打印结果为: hello I am a good man
Swift的可变参数如下:
func appendString(string: String, otherString: String, _ moreStrings: String...) -> String {
var resurltString = string + " " + otherString
resurltString += moreStrings.reduce("", { (x, y) -> String in
x + " " + y
});
return resurltString
}
调用:
xxx.appendString(string: "Hello", otherString: "I", "am", "a", "good", "man")
打印结果和上面一致。Nice!!!