当我创建一个函数时,我可以通过赋予它一个默认值来使参数成为可选参数,如下所示:
func foo(bar: String = "foobar") {}
我想用完成块做同样的事情(使其成为可选项)。我尝试过以下方法:
func foo(completionBlock: (foo: String) -> () = () -> ())
func foo(completionBlock: (foo: String) -> () = (foo: String) -> ())
func foo(completionBlock: (foo: String) -> () = ((foo: String) -> ()))
func foo(completionBlock: (foo: String) -> () = ((foo: String) in))
func foo(completionBlock: (foo: String) -> () = {(foo: String) in})
我该怎么做?
编辑:
这是一个重复的问题,对不起。但是,我无法在原始问题中找到解决方案。所以nathan的答案是最好的答案
答案 0 :(得分:32)
如果您想默认为// Create the necessary arrays
NSMutableArray<BarChartDataEntry *> *cyValues = [NSMutableArray array], *lyValues = [NSMutableArray array];
NSMutableArray<NSString *> *dates = [NSMutableArray array];
NSMutableArray<UIColor *> *divColors = [NSMutableArray array];
// Loop through your data, populating your charts datasource, colors, ect...
for (int i = 0; i < varData.count; i++) {
[dates addObject:[CR convertDate:[varData[i]HOUR] inputFormat:@"H" outputFormat:@"h a"]];
[cyValues addObject:[[BarChartDataEntry alloc] initWithValue:[[varData[i]CYSALES] floatValue] xIndex:i]];
[lyValues addObject:[[BarChartDataEntry alloc] initWithValue:[[varData[i]LYSALES] floatValue] xIndex:i]];
[divColors addObject:[UIColor getColorForHourlyChartData:[[varData[i]CYSALES] floatValue] andValue2:[[varData[i]LYSALES] floatValue]]];
}
// init your charts dataSource with the values from above
divChartData = [[CombinedChartData alloc] initWithXVals:dates];
divChartData.barData = [self setupBarChartWithValues:lyValues withLabel:@"Last Year" withColor:[UIColor chartLY] withColorArray:nil];
divChartData.lineData = [self setupLineChartWithValues:cyValues withLabel:@"Current Year" withColor:[UIColor chartCY] withColorArray:divColors];
// Reload tableView
[self.tableView reloadData];
:
Combined
如果您的默认完成块非常简单,您可以使用闭包:
barChart
如果您的默认完成块长于一行,最好将其分解为自己的函数:
lineChartView
答案 1 :(得分:31)
在Swift 3中:
+