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

これでよくわかる!Swiftのオプショナル

Sato Takeshi
February 28, 2016

 これでよくわかる!Swiftのオプショナル

iOS開発会議 in beez渋谷 47回目に発表した資料です。

Sato Takeshi

February 28, 2016
Tweet

More Decks by Sato Takeshi

Other Decks in Technology

Transcript

  1. 0QUJPOBMܕએݴ var a: Int? var b: Optional<Int> // Int?ɹͱಉ͡ҙຯ enum

    Optional<T> : Reflectable, NilLiteralConvertible { case None // nil ʹ૬౰͢Δ case Some(T) // T ܕʢૉͷܕʣͷ஋͕ೖΔʢInt ܕ΍ String ܕͷ஋ͳͲʣ } 0QUJPOBM5͸FOVNܕͰఆٛ
  2. 0QUJPOBMܕએݴ͢ΔͱOJM͕ೖͬͯ΋͍͍ var a: Int? a = nil //->nil͕ೖͬͯ΋େৎ෉ var b:

    Int // ඇ optional ܕ b = nil // -> Nil cannot be assigned to type 'Int' ඇPQUJPOBMܕʹOJMΛ୅ೖ͠Α͏ͱ͢ΔͱɺίϯύΠϥΤϥʔ͕ൃੜ͢Δɻ 0QUJPOBMܕͷॳظ஋͸OJM
  3. 0QUJPOBMܕͱඇ0QUJPOBMܕ͸ผͷܕ var unoptionalInt: Int = 1 print(unoptionalInt + 2) //

    -> 3 var optionalInt : Int? = 1 print(optionalInt + 2) //Value of optional type 'Int?' not unwrapped; 0QUJPOBMܕΛ࢖͏ʹ͸Ξϯϥοϓ͕ඞཁ
  4. 'PSDFEVOXSBQQJOH var optionalInt : Int? = 1 print(optionalInt! + 2)

    0QUJPOBMܕͷม਺ͷޙΖʹʮʯΛ͚ͭΔ OJMͩͬͨΒϥϯλΠϜΤϥʔ
  5. 0QUJPOBMDIBJOJOH class Room { var adress : String = "ौ୩۠"

    } class Person { var room : Room? } var aperson = Person() aperson.room?.adress = "໨ࠇ۠" aperson.room = Room() print(aperson.room?.adress) ʮ ʯΛ࢖ͬͯΞϯϥοϓ͢Δ͜ͱ ΞϯϥοϓΛͨ͠ޙʹɺ࠷ऴతͳ໭Γ஋ΛPQUJPOBMܕʹϥοϓͯ͠ ͔Βฦ͢ɻ
  6. 0QUJPOBM#JOEJOH if let adress = aperson.room?.adress{ print(adress) }else{ print("ॅॴ͕ొ࿥͞Ε͍ͯ·ͤΜ") }

    while let adress = aperson.room?.adress{ print(adress) break } JG΍XIJMFจͷ৚݅ࣜͰએݴ͞ΕɺPQUJPOBMܕͷม਺Λ୅ೖ͞Εͨ ม਺͸ɺඇPQUJPOBMܕʹͳΔɻ ͜ΕΛʮPQUJPOBMCJOEJOHʯͱݴ͏
  7. ൺֱԋࢉࢠ var wrappedInt: Int? = 1 // Optional ܕ print(wrappedInt

    == 1) // -> true print(wrappedInt >= 1) // -> true print(wrappedInt > 1) // -> false print(wrappedInt <= 1) // -> true print(wrappedInt < 1) // -> false print(wrappedInt != 1) // -> false wrappedInt = nil print(wrappedInt == 1) // -> false ൺֱԋࢉࢠΛ࢖͏ͱɺPQUJPOBMܕͷม਺͕ࣗಈతʹΞϯϥοϓ͞Ε Δɻ OJM͕ೖͬͯ΋Τϥʔʹ͸ͳΒͳ͍
  8. *NQMJDJUMZ6OXSBQQFE0QUJPOBMܕͰએݴ /**implicitly unwrapped optional*/ var assumedString: String! = "An implicitly

    unwrapped optional string." let implicitString: String = assumedString // no need for an exclamation mark” print(implicitString) /*ΦϓγϣφϧόΠϯσΟϯά΋Ͱ͖Δ*/ if let definiteString = assumedString { print(definiteString) } ࣗಈతʹΞϯϥοϓ͞ΕΔPQUJPOBMܕ ʮʯͰએݴ͢Δ
  9. *NQMJDJUMZ6OXSBQQFE0QUJPOBMܕͰએݴ var implicityInt: Int! var implicityInt2: ImplicitlyUnwrappedOptional<Int> // Int! ͱಉ͡ҙຯ

    ʮʯ͸*NQMJDJUMZ6OXSBQQFE0QUJPOBM5ͷγϯλοΫεγϡΨʔɻ *NQMJDJUMZ6OXSBQQFE0QUJPOBM5͸FOVNܕͰఆٛ͞Ε͍ͯΔ enum ImplicitlyUnwrappedOptional<T> : Reflectable, NilLiteralConvertible { case None // nil ʹ૬౰͢Δ case Some(T) // T ܕʢૉͷܕʣͷ஋͕ೖΔʢInt ܕ΍ String ܕͷ ஋ͳͲʣ }