LoginSignup
1
0

More than 5 years have passed since last update.

Array<独自クラス> で特定メンバ変数のsumを出す

Last updated at Posted at 2017-10-09

経緯

Realmで取得したクラスの配列でInt型のメンバ変数の sum を出したかったのですが、
一工夫必要だったのでメモがてら残しておきます

実例

前提

sectionData: realmに入れてるデータクラスの配列
gain : realmに入れてるデータクラスのうち、Intのデータ

サンプルコード

やっていることとしては、各要素の中で、
必要な値だけの配列を作ってやって、それからreduceをする

let gains = sectionData.map{ $0.gain }.reduce(0){
    $0 + $1
}

メモ

本当はこんな感じでできたらいいのに/できるはず?

let gains = sectionData.reduce(0){
    $0.gain + $1.gain
}

結構色々調べながら上記のようなreduceのワンライナーでできないか
色々試したのですが、だめでした。
なぜこれでできないのか、後日調査します。

追記

コメントで頂いた記述がもっとスッキリしていたのでこちらのほうがいいです。

let gains = sectionData.reduce(0){
    $0 + $1.gain
}
1
0
2

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