22
15

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】インデックス付きでmap, reduce, filterを使ってみる

Last updated at Posted at 2015-08-19

Swift 3.0

使いどころがあるかは分かりませんが実験的に。
参考: Swiftでのenumerateの使い方

map


let array = [1, 2, 3, 4]
let m = array.enumerated().map { "\($0.0): \($0.1)" } // インデックスと要素のペア
print(m)
// ["0: 1", "1: 2", "2: 3", "3: 4"]

reduce


let array = [1, 2, 3, 4]
let r = array.enumerated().reduce(0) { $0 + $1.0 * $1.1 } // インデックスと要素の積の総和
print(r)
// 20 <- 0*1 + 1*2 + 2*3 + 3*4

filter


let array = [1, 2, 3, 4]
let f = array.enumerated().filter { $0.0 * $0.1 > 3 }.map { $0.1 } // インデックスと要素の積が3より大きいもの
print(f)
// [3, 4]

最後に

enumerateでの値の受け取り方についての詳しい実験は別の記事にしたいと思います。

【Swift】enumerateを使ったときの値の受け取り方

追記: 記事にしました。

22
15
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
22
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?