LoginSignup
8
5

More than 5 years have passed since last update.

Swiftでfor文を使わないで書く

Posted at

この記事が話題になっていたのでSwiftでのサンプルコードを示します。


問題: 0から100未満の偶数の和を求めよ。

for文を使った解答
var t = 0
for i in 0..<100 {
    if i % 2 == 0 {
        t += i
    }
}
print(t) // 2450
関数型を使った解答
print((0..<100).filter { $0 % 2 == 0 }.reduce(0, +)) // 2450

自分としては、map, filter, reduceあたりを使って簡潔に関数型で書けるなら、for文は使わない方が良いと思うので上記の記事に賛成です。

8
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
8
5