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

Mobile Programming Optional

Mobile Programming Optional

モバイルプログラミングの授業で使うスライドです

yuichiro_takahashi

December 19, 2018
Tweet

More Decks by yuichiro_takahashi

Other Decks in Technology

Transcript

  1. ςΩετ OPTIONAL TYPE? ▸ Swiftʹසൟʹग़ͯ͘Δ ? ΍ ! ϚʔΫͷਖ਼ମ ▸

    Swift͚ͩͰͳ͘ϞμϯͳݴޠʹΑ͘ݟΒΕΔ nil (null) Λ҆શʹѻ͏ҝͷػೳ ▸ ී௨ͷ஋͚ͩͰͳ͘ nil ΋ೖΕΔ͜ͱ͕Ͱ͖ΔίϯςφͷΑ͏ͳ΋ͷ ▸ ܕఆٛͷࡍʹ຤ඌʹ ? Λ͚ͭΔ͜ͱͰOptional Type ʹͳΔ ▸ SwiftͰ͸Optionalͱͯ͠ఆٛ͞Εͨม਺ͷΈnilΛ୅ೖ͢Δ͜ͱ͕Ͱ͖Δ ▸ Optional TypeʹͳΔͱී௨ͷܕͱͯ͠͸࢖͑ͳ͍ͷͰҰ౓Optional͔Β σʔλΛऔΓग़͢ඞཁ͕͋Δ
  2. ςΩετ ࣮ࡍͷίʔυ // ม਺ͷ৔߹ var indexOrNil: Int? = 0 //

    ͜ͷΑ͏ʹ΋ॻ͚Δ var optionalNum: Optional<Int> = 10 // ؔ਺ͷ৔߹ func getImage(named: String?) -> UIImage? { // লུ ... } // ͜Ε͸Ͱ͖ͳ͍ print("added: \(optionalNum + 10)”) // ͳΜΒ͔ͷํ๏ͰOptional͔Β஋ΛऔΓग़͢ඞཁ͕͋Δ(ࠓճ͸!ϚʔΫ) print("added: \(optionalNum! + 10)”)
  3. ςΩετ FORCED UNWRAP? ▸ ଟ෼͜Ε͕Ұ൪͓खܰͳํ๏ ▸ optionalͰఆٛ͞Εͨม਺ͷ຤ඌʹ ! ϚʔΫΛ͚ͭΔ͚ͩ ▸

    ͨͩ͠஋͕͋Δ͔nil͔Ͱ͋Δ͔ʹؔΘΒͣڧ੍తʹOptionalΛ unwrapͯ͠͠·͏ ▸ ͦͷҝnilͩͬͨ৔߹͸ϓϩάϥϜ͕Ϋϥογϡ͢Δ ▸ ͲΜͳͱ͖΋஋͕࣮֬ʹೖ͍ͬͯΔͱ͍͏͜ͱ(ઈରnilʹ͸ͳΒͳ͍ ͱ͍͏ࣄ)͕อূͰ͖Δ৔߹ͷΈ࢖͍·͠ΐ͏
  4. ςΩετ ࣮ࡍͷίʔυ // ม਺ͷ৔߹ var nilNumber: Int? = nil //

    ͜ͷΑ͏ʹ΋ॻ͚Δ var optionalNum: Optional<Int> = 10 //ม਺ optionalNum ͷ຤ඌʹ!ϚʔΫΛ͚ͭͯ஋ΛऔΓग़͢ print("added: \(optionalNum! + 10)”) //͜Ε͸Ϋϥογϡʂ print("added: \(nilNumber! + 10)”)
  5. ςΩετ NIL COALESCING OPERATOR? ▸ ͪ͜Β΋ඇৗʹ͓खܰͳํ๏͔ͭ҆શ ▸ optionalͰఆٛ͞Εͨม਺ͷޙΖʹ ?? <defaultValue>

    Λͬͭ͘ ͚Δ ▸ ?? ԋࢉࢠ͸஋͕͋Ε͹ͦͷ஋Λฦ͠ɺnilͰ͋Ε͹ࢦఆͨ͠ defaultValueΛฦ͢ ▸ defaultValue ͑͞༻ҙͰ͖Ε͹҆શ͔͓ͭखܰʹ Unwrap Ͱ͖Δ ▸ get or elseͱݺ͹ΕΔ͜ͱ΋͋Δ
  6. ςΩετ ࣮ࡍͷίʔυ // ม਺ͷ৔߹ var nilNumber: Int? = nil //

    ͜ͷΑ͏ʹ΋ॻ͚Δ var optionalNum: Optional<Int> = 10 // ม਺ optionalNum ͷޙΖʹ ?? ϚʔΫΛ͚ͭͯ஋ΛऔΓग़͢ // ม਺ optionalNum ͕ nil ͩͬͨΒ 0 ʹͳΔ print("added: \((optionalNum ?? 0) + 10)”)
  7. ςΩετ OPTIONAL BINDING? ▸ ԋࢉࢠΛ࢖͏ํ๏ʹൺ΂Δͱίʔυྔ͸૿͑Δ͕ͱͯ΋҆શ ʹѻ͑Δ ▸ if let ΍

    guard let, switch Λ࢖ͬͯ unwrap ͢Δํ๏ ▸ ͦΕͧΕܗ͸ҧ͏͕શͯ optional ͷத਎Λ৽͍͠ఆ਺ʹଋ റ(bind)͢Δ͜ͱͰunwrap͢Δ ▸ Ұ൪Α͘࢖͏ํ๏͔΋