関数を引数として渡す書き方のポイント

 関数を引数として渡す書き方のポイント

Ac3c0c2b458cdf0fe6a6e98a46e34322?s=128

Yoshikuni Kato

September 17, 2017
Tweet

Transcript

  1. ؔ਺ΛҾ਺ͱͯ͠౉͢ॻ͖ํͷϙΠϯτ Ճ౻༝܇ / @yoshikuni_kato iOSDC 2017 2017/09/17 1

  2. Who am I? • Ճ౻༝܇ʢYoshikuni Katoʣ @yoshikuni_kato • iOSΤϯδχΞʢ2.5 yearsʣ

    • Yahoo! Japan -> Φϋί • ʮϥδ΁͐ʯ͘Μ → • Interests: ઃܭ / FRP / Coordinator PaFern / UI࣮૷ 2
  3. func%onalʹॻ͘܏޲ • func&onalʹॻ͘͜ͱ͕૿͖͑ͯͨ • FRP (RxSwi3 / Reac&veSwi3) • map

    / filter / reduce • if΍for͕ݮΔ • એݴతʹॻ͚Δ 3
  4. ͜ͷLTͰγΣΞ͢Δ͜ͱ • ؔ਺ΛҾ਺ͱͯ͠౉͢৔߹ͷॻ͖ํ → গ͠ͷมߋ͚ͩͲɺΑΓએݴతʹݟ͑Δํ๏ • arrayͷmapΛྫʹ 4

  5. ॻ͖ํ̍ - ΫϩʔδϟΛ௚઀ॻ͘ let array: [Int] = [1, 2, 3]

    array.map { number -> Int in return number * 2 } 5
  6. arrayͷmapͷఆٛ func map<T>(_ transform: (Element) throws -> T) rethrows ->

    [T] • mapͷҾ਺ɿElementΛड͚औͬͯTΛฦ͢Ϋϩʔδϟ • ؔ਺͸ɺ໊લ෇͖ͷΫϩʔδϟͱଊ͑ΒΕΔ • ؔ਺ࣗମΛ౉͢͜ͱ͕Ͱ͖Δ 6
  7. ॻ͖ํ̎ - ؔ਺Λ౉͢ // ઌʹؔ਺Λఆٛ func twoTimes(of number: Int) ->

    Int { return number * 2 } let array: [Int] = [1, 2, 3] array.map(twoTimes) // ؔ਺Λ౉͢ 7
  8. ύϥϝʔλʔ͕ෳ਺͋Δ৔߹ func someFunc(a: Int, b: Int) -> String { return

    "a = \(a), b = \(b)" } let array: [Int] = [1, 2, 3] array .map { number -> (a: Int, b: Int) in return (a: number, b: number) // Ұ୴λϓϧʹ͢Δ } .map(someFunc) 8
  9. ΠχγϟϥΠβͷ৔߹ struct Sample { let number: Int init(number: Int) {

    self.number = number } } 9
  10. ॻ͖ํ̍ - ΫϩʔδϟΛ௚઀ॻ͘ let array: [Int] = [1, 2, 3]

    array.map { number -> Sample in return Sample(number: number) } 10
  11. ॻ͖ํ̎ - ؔ਺Λ౉͢ let array: [Int] = [1, 2, 3]

    array.map(Sample.init) • ΠχγϟϥΠβ(.init) = ͦͷObjectΛฦؔ͢਺ 11
  12. ҧ͍ 1 array.map { number -> Sample in return Sample(number:

    number) } array.map(Sample.init) 12
  13. ҧ͍ 2 array .map { number -> Int in return

    number * 2 } .map { number -> Sample in return Sample(number: number) } .map { sample -> Foo in return Foo(sample: sample) } array .map(twoTimes) .map(Sample.init) .map(Foo.init) 13
  14. ·ͱΊ • গ͠ॻ͖ํΛม͑Δ͚ͩͰɺΑΓએݴతʹॻ͚Δํ๏Λ঺հ • ׆༻ྫɿModel͔ΒViewModel΁ͷม׵ ɹ model.map(ViewModel.init) • ݁ՌతʹɺॲཧΛؔ਺ʹ੾Γग़͍ͯ͘͜͠ͱʹͳΔ •

    ؔ਺Λ౉͍ͯ͘͠ײ֮ʢखଓ͖ܕͷײ͔֮Βঃʑʹ཭ΕΔʣ 14
  15. ࢀߟ • Connec'ng View Controllers, Swi3 Talk1 • From Run'me

    Programming to Func'ons, Swi3 Talk2 2 h$ps:/ /talk.objc.io/episodes/S01E19-from-run@me-programming-to-func@ons 1 h$ps:/ /talk.objc.io/episodes/S01E05-connec;ng-view-controllers 15
  16. ͓·͚ func someFunc(a: Int, b: Int) -> String { return

    "a: \(a), b: \(b)" } // λϓϧ͸౉ͤͳ͍ let parameters = (a: 0, b: 0) someFunc(parameters) // !ʢswift3~ʣ // mapͩͱ౉ͤΔ let array: [(Int, Int)] = [(0, 0)] array.map(someFunc) // "ʢswift3Ͱ΋ʣ • ͳͥॻ͚Δͷ͔෼͔͍ͬͯΔਓ͕͍ͨΒڭ͍͑ͯͩ͘͞ 16