LoginSignup
2
2

More than 5 years have passed since last update.

Swiftのreduceで集合の条件確認用関数を書いた

Posted at

Functional Snippet #5: Reduce · objc.io
allの例があるのだか、
他にもRubyやlodashなどで良く使用する条件判定用の集合関数の簡易版を勉強がてらreduce関数を使用して実装してみました。1
(コレクションの各要素に対して、クロージャーを評価する方式ではないです。)

実際は、クロージャーを評価する方式の
pNre/ExSwiftとか、ankurp/Dollar.swiftが扱いやすいと思います。

  • all

全ての要素がtrueかどうか

let all: [Bool] -> Bool = { $0.reduce(true, combine: { $0 && $1 }) }
all([true,true,true])  // true
all(Array(0...5).map { $0 % 2 == 0 }) // false
  • any

一つでもtrueかどうか

let any: [Bool] -> Bool = { $0.reduce(false, combine: { $0 || $1 }) }
any([false,false,true])  // true
any(Array(0...5).map { $0 > 5 }) // false
  • none

全てfalseかどうか

let none: [Bool] -> Bool = { $0.reduce(false, combine: { b1, b2 -> Bool in !b1 && !b2 }) }
none([false,false,false]) // true
none([true,false,false])  // false
  • one

どれか一つだけtrueかどうか
(reduce使っていない‥)

let one: [Bool] -> Bool = { $0.filter({ $0 }).count == 1 }
one([false,false,true]) // true
one([false,true,true])  // false

まとめ

reduceは、

  1. 一時変数を使わない
  2. 再帰で処理の実体が見易い

ので簡潔に記述できる。

YOUたち!RubyでinjectしちゃいなYO!
上記の記事でArrayの組み込みメソッドを再実装しているので、
SwiftのArrayの組み込みのメソッドも再実装してみようと思います。

2
2
1

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
2