Swift: 可变参数
转自: https://addicechan.github.io/... 在 使用可变参数,其实很简单。就是在参数类型加上 小二。。上代码~~~ // 多数字相加 func add(_ values: Int...) -> Int { return values.reduce(0){ $0 + $1 } } print(add(1,5,8,9)) // 23 再比如,可以封装一个 extension UIAlertController { class func show(_ vc: UIViewController?,title: String,msg: String,style: UIAlertControllerStyle,btns: String...,completionHandler:@escaping ((_ btnIndex: Int) -> Void)) { let alertController : UIAlertController = UIAlertController(title: title,message: msg,preferredStyle: style) for (index,element) in btns.enumerated() { alertController.addAction(UIAlertAction(title: element,style: .default,handler: { _ in completionHandler(index) })) } if style == .actionSheet { alertController.addAction(UIAlertAction(title: "cancel",style: .cancel,handler: nil)) } vc?.present(alertController,animated: true,completion: nil) } } // 使用 UIAlertController.show(self,title: "Alert",msg: "show alert",style: .alert,btns: "previous","next") { index in print(index) } 不过,可变参数无法用于
小二,继续上代码~~~ - (NSString *)add:(NSString *)value,... NS_REQUIRES_NIL_TERMINATION { NSMutableString *result = [NSMutableString string]; [result appendString:value]; if (value) { va_list values; // values 会从 value 的指针地址开始取值,直至nil va_start(values,value); id tempValue; while((tempValue = va_arg(values,NSString *))) { [result appendString:tempValue]; } // 记得清空 va_end(values); } return result; } 使用 写完这个方法后,只能感叹下 func add(_ values: String...) -> String { return values.reduce(""){ $0 + $1 } } 这样几行代码,就已经实现了上述 写这篇的根源,其实是在翻(gen)看(ben) 算是又明白了一些。但愿不太迟。 哭瞎了。。。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |