swift3.0に向けて enumerateを使い始めよう

33

Upload: motoki-narita

Post on 08-Jan-2017

6.413 views

Category:

Mobile


0 download

TRANSCRIPT

自己紹介

• @mo_to_44

• 株式会社ネクストで  HOME’Sという 不動産検索アプリのiOSエンジニアをやっています

個人でもアプリ作ってます

  リボカメ - Revolver Camera

• リボルバーを模したUI

• フィルターをリアルタイムで切り替え、確認できる

• Apple Watch対応

swift-evolutionhttps://github.com/apple/swift-evolution

Swift 3.0 proposal

• https://github.com/apple/swift-evolution/tree/master/proposals から見ることができる

• 0004 と 0007 が気になった

0004: Remove the ++ and -- operatorsStatus: Accepted

0007: Remove C-style for-loops with conditions and incrementers

Status: Under review (December 7, 2015 -- December 10, 2015)

Today

0007: Remove C-style for-loops with conditions and incrementers

Status: Accepted

と、いうことで

こんなんが書けなくなる😱

困りそうなこと

あんまりない😜for-in, forEach, map, filter よりどりみどり

Swift Advent Calendar 2015 2日目にまとめましたhttp://qiita.com/mo_to_44/items/cf83b22cb34921580a52

ちょっと困りそうなこと

• 配列内の要素のindexを取得したい

• indexが奇数の要素だけ取得したい などなど

などなど、indexによってデータを取得、更新したり、indexが配列を操作する際に重要な場合

indexが奇数の要素だけ取得

1. 空の配列 newArray を用意 2. for-inで各要素のindexを取得 3. indexが奇数の要素を newArray に追加

長っ

こんな時に

enumerateが使える

enumerate

• SequenceType Protocolに定義されている

• indexと要素のペア(タプル)の配列を取得することができる

indexが奇数の要素だけ取得enumerate使用版

1. 空の配列 newArray を用意 2. enumerateを使用し、indexと要素のタプルの配列のfor-inを回す

3. indexが奇数の要素を newArray に追加

まだちょっと長い

indexが奇数の要素だけ取得enumerate使って1行に

1. enumerateを使用し、indexが奇数のタプルをfilterで絞り込み

2. mapで要素のみを取り出す

(index, element)$0.0 $0.1

タプルの要素へのアクセス

indexが奇数の要素だけ取得enumerate使って1行に

1. enumerateを使用し、indexが奇数のタプルをfilterで絞り込み

2. mapで要素のみを取り出す

シンプル 👍

まとめ

enumerate• SequenceTypeのExtensionで定義されている

• index と 要素のペア(タプル)の配列を取得できる

Swift 3.0• ++ と -- がなくなる

• C言語スタイルのfor文がなくなる

Swift 3.0に向けて• C言語スタイルのfor文ではなく、enumerateを積極的に使っていく

• 同様に ++ や -- も使わないようにする

• swift-evolution/proposal に目を通して、なくなるかもしれない文法はなるべく使わないようにする

おわり