Help us understand the problem. What is going on with this article?

【Swift】reduceを使ってInt型配列の中身の合計値を取得する(自分用メモ)

配列に入っている数値をスマートに合計したかった.
reduceを使えば一行でできることがわかった.
足し算だけでなく、引き算や掛け算にも応用できる.

配列内の数値の合計値を取得する

reduce.swift
let array: [Int] = [1, 2, 3, 4, 5]
let result: Int = array.reduce(0) { $0 + $1 }

print(result)
// 結果 -> 15

reduceでは{}内の処理が要素数の分だけ繰り返される.

1回目の動き

reduce()の中身は初期値.
自身で好きな値を入れられる.

reduce.swift
reduce(0)
// -> 初期値として 0 を代入している.
$0
// -> 初期値 0 が代入される.
$1
// -> 配列の要素が左(Indexが0の値)から代入される.(ここではarray[0] = 1)

n回目の動き

reduce.swift
$0
// -> (n-1)回目の計算結果が代入される.
$1
// -> array[(n-1)]の値が代入される.

合算(+)以外の計算

{}の中身を-*に書き換えれば繰り返し計算ができる.

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away