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

Swift flatMap

USAMI Kosuke
February 28, 2017

Swift flatMap

USAMI Kosuke

February 28, 2017
Tweet

More Decks by USAMI Kosuke

Other Decks in Programming

Transcript

  1. Op#onal ͷ flatMap • ม׵લ : Optional<T> • ม׵ॲཧ :

    T -> Optional<U> • flatMap : Optional<T> -> Optional<U> • ม׵લ͕ non-nil ͳΒม׵ॲཧΛద༻͢Δ • ม׵લ͕ nil ͳΒม׵ॲཧΛద༻͠ͳ͍
  2. ྫ • ม׵લ : Optional<String> • ม׵ॲཧ : String ->

    Optional<Int> : { Int($0) } • string.flatMap { Int($0) } • "123" -> Int("123") -> 123 • "abc" -> Int("abc") -> nil • nil -> nil
  3. nil ͷೖྗΛҙࣝ͠ͳ͍͍ͯ͘ // string ͸ Optional ͚ͩͲɾɾɾ let string: String?

    = "123" let integer: Int? = string.flatMap { Int($0) // $0 ͸ unwrap ͞Ε͍ͯΔ }
  4. if let Ͱॻ͘ͱ৑௕ʹͳΔ let string: String? = "123" let integer:

    Int? if let string = string { integer = Int(string) } else { integer = nil }
  5. Array ͷ flatMap (1) • ม׵લ : Array<T> • ม׵ॲཧ

    : T -> Array<U> • flatMap : Array<T> -> Array<U>
  6. ྫ • ม׵લ : Array<Int> • ม׵ॲཧ : Int ->

    Array<Int> : { [$0, $0 * 10] } • [1, 2, 3].flatMap { [$0, $0 * 10] } • 1 -> [1, 10], 2 -> [2, 20], 3 -> [3, 30] • [1, 10, 2, 20, 3, 30]
  7. Op#onal ͱ Array ͷ flatMap ൺֱ • ม׵લ : Optional<T>

    • ม׵ॲཧ : T -> Optional<U> • flatMap : Optional<T> -> Optional<U> • ม׵લ : Array<T> • ม׵ॲཧ : T -> Array<U> • flatMap : Array<T> -> Array<U>
  8. flatMap ͷجຊܗ • ܕ T ΍ U ͕ೖͬͨԿΒ͔ͷശʢBoxʣ͕͋Δͱ͖ʹ • ม׵લ

    : Box<T> • ม׵ॲཧ : T -> Box<U> • flatMap : Box<T> -> Box<U>
  9. Array ͷ flatMap (2) • ม׵લ : Array<T> • ม׵ॲཧ

    : T -> Optional<U> • flatMap : Array<T> -> Array<U> • ม׵ॲཧͷ݁Ռ͕ non-nil ͷ΋ͷ͕ Array ͷཁૉʹͳΔ • ม׵ॲཧͷ݁Ռ͕ nil ͷ΋ͷ͸ࣺͯΒΕΔ
  10. ྫ • ม׵લ : Array<String> • ม׵ॲཧ : String ->

    Optional<Int> : { Int($0) } • ["123", "abc"].flatMap { Int($0) } • "123" -> 123, "abc" -> nil • [123]
  11. Array ͷ 2 ͭͷ flatMap ͷؔ܎ • flatMap (2) ͸

    flatMap (1) Ͱ࣮ݱͰ͖Δ • non-nil Λฦ͢୅ΘΓʹ1ཁૉͷ Array Λฦ͢ • nil Λฦ͢୅ΘΓʹۭͷ Array Λฦ͢ • flatMap (2) ͷํ͕ίʔυ͕γϯϓϧʹͳΔ • flatMap (1) ͸࣮͸͋Μ·Γ࢖Θͳ͍
  12. ׆༻ྫ • ["A", "B", nil, "C"] : [String?] • ͔͜͜Β

    nil ΛऔΓআ͍ͨ [String] ͕ཉ͍͠ // flatMap ͳ͠ͳΒɺ͜Μͳײ͡Ͱॻ͘ʁ ["A", "B", nil, "C"] .filter({ $0 != nil }) as! [String]
  13. ׆༻ྫ // ୯ʹ͜͏ॻ͚͹ྑ͍ ["A", "B", nil, "C"].flatMap { $0 }

    • ม׵લ : Array<Optional<String>> • ม׵ॲཧ : Optional<String> -> Optional<String> • flatMap : Array<Optional<String>> -> Array<String>
  14. ࢀߟɿଞʹ flatMap ͕࢖͑Δ΋ͷ • Result ܕʢan+typical/Resultʣ • Op+onal ͱ΄΅ಉ͡ʢnil ͷ୅ΘΓʹ۩ମతͳ

    Error Λฦ͢ʣ • Observable ܕʢRxSwi:ʣ • ඇಉظετϦʔϜɺ్தͰΤϥʔʹͳͬͨ৔߹ͷରԠ͕༰қ