美文网首页
多种方式求数组的和

多种方式求数组的和

作者: liang1030 | 来源:发表于2024-11-08 07:40 被阅读0次

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")

相关文章

网友评论

      本文标题:多种方式求数组的和

      本文链接:https://www.haomeiwen.com/subject/jextjjtx.html