多种方式求数组的和

2024-11-08  本文已影响0人  liang1030

1,遍历数组

2,使用reduce高阶函数

let arr = [2,3,4,5]
let result = arr.reduce(0) {
return $0 + $1
}
print(result) //14

3,通过KVC实现

OC :

NSArray *values = @[@72,@78,@70,@72,@73,@76];
NSNumber *avg = [values valueForKeyPath:@"@avg.self"];
NSNumber *sum = [values valueForKeyPath:@"@sum.self"];
NSNumber *max = [values valueForKeyPath:@"@max.self"];
NSNumber *min = [values valueForKeyPath:@"@min.self"];

swift :

let avg = values.value(forKeyPath: "@avg.self")
let sum = values.value(forKeyPath: "@sum.self")
let max = values.value(forKeyPath: "@max.self")
let min = values.value(forKeyPath: "@min.self")

上一篇 下一篇

猜你喜欢

热点阅读