Upgrade to Pro — share decks privately, control downloads, hide ads and more …

SwiftのmapとflatMapを雑に解説する / map and flatMap on Swift

473b12ebcfb79adfaef97796e94fc25c?s=47 Hiron
December 29, 2015

SwiftのmapとflatMapを雑に解説する / map and flatMap on Swift

tokushima.app で発表 **しなかった** スライドです。

2015年の年末あたりに、次のtokushima.appで発表しようと考えて作ったのですが、会場の都合でしばらく開かれなくて完全にタイミングを逃し、次に開かれたときには別のことを発表しました😓

473b12ebcfb79adfaef97796e94fc25c?s=128

Hiron

December 29, 2015
Tweet

More Decks by Hiron

Other Decks in Programming

Transcript

  1. 4XJGUͷNBQͱqBU.BQΛ ࡶʹղઆ͢Δ !IJSPOZUJDʢҰٶߒڭʣ UPLVTIJNBBQQ

  2. "SSBZͷNBQ let array: [Int] = [1, 3, 8] array.map {x

    in x + 1}
  3. ͪΐͬͱ୤ઢ array.map {x in x + 1} array.map({ (x: Int)

    -> Int in return x + 1 })
  4. "SSBZͷNBQ let array: [Int] = [1, 3, 8] array.map {x

    in x + 1}
  5. "SSBZͷNBQ let array: [Int] = [1, 3, 8] array.map {x

    in x + 1}    f(x) f(x) f(x) f(x) = x + 1   
  6. "SSBZͷNBQ let array: [Int] = [1, 3, 8] array.map {x

    in [x, x + 1]}
  7. "SSBZͷNBQ let array: [Int] = [1, 3, 8] array.map {x

    in [x, x + 1]}    f(x) f(x) f(x) f(x) = [x, x + 1]      
  8. "SSBZͷqBU.BQ let array: [Int] = [1, 3, 8] array.flatMap {x

    in [x, x + 1]}    f(x) f(x) f(x) f(x) = [x, x + 1]      
  9. 0QUJPOBMͷNBQ let value: Int? = … value.map {x in x

    + 1}
  10. ·ͨ·ͨ୤ઢ [Int] Array<Int> Int? Optional<Int>

  11. 0QUJPOBMͷNBQ let value: Int? = … value.map {x in x

    + 1}
  12. 0QUJPOBMͷNBQ let value: Int? = … value.map {x in x

    + 1} let value: Int? = 16 value.map {x in x + 1}  f(x)  let value: Int? = nil value.map {x in x + 1} OJM OJM
  13. ΞΠςϜ਺ σʔλ͕ͳ͍ ΞΠςϜ਺ σʔλ͕͋Δ "SSBZ <> <> 0QUJPOBM OJM /POF

     4PNF  "SSBZͱ0QUJPOBM  OJM 
  14. NBQ let array: [Int] = [] array.map {x in x

    + 1} -> [] let array: [Int] = [16] array.map {x in x + 1} -> [17] let value: Int? = nil value.map {x in x + 1} -> nil let value: Int? = 16 …Int?(16) value.map {x in x + 1} -> 17 …Int?(17)
  15. qBU.BQ let array: [Int] = [] array.flatMap {x in [x

    + 1]} -> [] let array: [Int] = [16] array.flatMap {x in [x + 1]} -> [17] let value: Int? = nil value.flatMap {x in Int?(x + 1)} -> nil let value: Int? = 16 …Int?(16) value.flatMap {x in Int?(x + 1)} -> 17 …Int?(17)
  16. 0QUJPOBMͷqBU.BQ let value: Int? = … value.flatMap {x -> Int?

    in if (x < 1) { return nil // ܭࢉࣦഊ } else { return x - 1 } }
  17. ·ͱΊ func plusOne(x: Int) -> Int { return x +

    1 } let array: [Int] = [1, 3, 8] array.map(plusOne) let value: Int? = 16 value.map(plusOne) w NBQ͸ശ͔Βग़ͯ͠ɺؔ਺Λద༻ ͯ͠ശʹೖΕΔɻ w qBU.BQ͸ശ͔Βग़ͯ͠ɺؔ਺Λ ద༻ͯ͠ϑϥοτʹശʹೖΕΔɻ w NBQ qBU.BQΛ࢖͏ͱɺͦ͜ʹ ౉͞ΕΔؔ਺͸֎ଆͷੈքΛҙࣝ ͠ͳ͍͍ͯ͘ʂ
  18. ࢀߟαΠτ w 4XJGUͷ0QUJPOBMܕΛۃΊΔ
 IUUQRJJUBDPNLPIFSJUFNTDGCBEBCG w Ϟφυʹ͍ͭͯ4XJGUͰઆ໌ͯ͠Έͨ
 IUUQRJJUBDPNLPIFSJUFNTGGGDECGBDG w +BWBͷ0QUJPOBMͷϞφυతͳ࢖͍ํ
 IUUQRJJUBDPNLPIFSJUFNTGBECBECG