2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Swift】配列内の要素の合計

2
Posted at

使用例

配列内の要素を求めるときに、使えそうなものを備忘録として残しておこうと思いました。タプル型を例に以下に記述していきます。

Zoo.swift
//定義
var zoo:[(label: String, value: Int)] = [
    (label: "リンゴ", value: 100),
    (label: "ゴリラ", value: 200),
    (label: "ラッパ", value: 300)
]

var sumValue = 0

1. for文


for item in zoo {
    sumValue += item.value
}

print(sumValue) //結果: 600

2. forEach


zoo.forEach { (item) in
    sumValue += item.value
}

print(sumValue) //結果: 600

3. reduce


let sum = zoo.reduce(0) { (result, item) -> Int in
    return result + item.value
}

print(sum) //結果: 600

※reduce補足

どのようにresultに値が代入されていくかについて説明します。


let sum = zoo.reduce(0) { (result, item) -> Int in
    print("result", result)
    print("value", item.value)
    return result + item.value
}

print("sum", sum)

//実行結果
result 0
value 100

result 100
value 200

result 300
value 300

sum 600

まとめ

今回備忘録としてまとめました。間違ってる部分などがあればご指摘ください。

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?