LoginSignup
9
5

More than 3 years have passed since last update.

[Swift]数字の配列から合計(sum)と平均(average)を計算

Posted at

swiftで数字の配列[1, 2, 3, 4, 5]などから合計と平均を出す機会が何度かあったのですが、毎回調べて実装していたので、まとめてみました。

Array.reduceを使う

数字の配列の合計を計算する場合、愚直にforEachを使う方法もありますが、Array.reduceを使うと簡潔に書けます。

[1, 2, 3, 4].reduce(0, +)
=>結果は10

第1引数は初期値(今回は0)です。
第2引数はオペレーターです。+-*/の4つが使えます。

参考
https://developer.apple.com/documentation/swift/array/2298686-reduce

extensionを使い、合計と平均を簡単に計算する

Int配列を例に、合計と平均を出すmethodを定義します。
Arrayのベース


extension Collection where Element == Int {

    func sum() -> Int {
        return reduce(0, +)
    }

    func average() -> Double {
        let value = sum()
        return Double(value) / Double(count)
    }

}

ソース

Intだけでなく、Float, Doubleの配列についてもextensionにしたソースを以下に置きました。
https://gist.github.com/usk2000/230d46869c9eba401978a8865d2f66fa

終わりに

今回はよく使う合計と平均について書いてみましたが、もっと数学的なものも書いてみたいですね。

参考

https://qiita.com/motokiee/items/cf83b22cb34921580a52
https://developer.apple.com/documentation/swift/array/2298686-reduce

9
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
5