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

Swift Optional Extension Tips

Swift Optional Extension Tips

503b1ca28b167b0d94a5992aad1a57b1?s=128

horimislime

August 17, 2016
Tweet

Transcript

  1. Optional Extension Tips Kyobashi.swift #2 @horimislime

  2. About • ! @horimislime • " ҿ৯ళ޲͚iPadΞϓϦʮτϨλʯ • ❤ ιϑτ΢ΣΞઃܭͱ͔ӡ༻ͱ͔

  3. Optionalͷ஍ຯͳπϥΈ

  4. Objective-C if (users.count == 0) { // nil͔ۭͩͬͨΒԿ͔͢Δ } if

    (name.length == 0) { // ໊લ͕nil͔ۭͩͬͨΒԿ͔͢Δ }
  5. Swift // Compile error ! if users?.isEmpty { // ...

    } if name?.isEmpty { // ... }
  6. OptionalΛѻ͏ࡍͷ͓໿ଋ guard let users = users where !users.isEmpty else {

    // nil͔ۭͩͬͨΒԿ͔͢Δ }
  7. Nil Coalescing • ୹͘ॻ͚Δ͕ɺͺͬͱݟͷՄಡੑʹ͚ܽΔ if array?.isEmpty ?? false { //

    ... } if !(str ?? "").isEmpty { // ... }
  8. θϩ൑ఆ • nilͷൺֱ͸ৗʹfalse • Objective-C→Swiftʹࣸܦ͢Δͱ௧͍໨ʹ // Objective-C if (str.count ==

    0) { ... } /// Swift if str?.characters.count == 0 { ... }
  9. ໰୊ • ܕ͕ݫີʹͳͬͨ΋ͷͷɺʮۭʯͷѻ͍͕໘౗ • nilͱۭͷঢ়ଶΛಉ͡Α͏ʹѻ͏ʹ͸ʁ

  10. Optional Extension • isNilOrEmptyతͳ΋ͷ • ௚઀Optional<String>ʹextension͸ੜ΍ͤͳ͍ // Error: 'Wrapped' constrained

    to non-protocol type 'String' extension Optional where Wrapped: String { var isNilOrEmpty: Bool { return self?.isEmpty ?? true } }
  11. Optional Extension • ಠࣗprotocolΛ༻ҙ͠ɺStringʹ४ڌͤ͞Δ protocol StringType { var isEmpty: Bool

    { get } } extension String: StringType {} extension Optional where Wrapped: StringType { var isNilOrEmpty: Bool { return self?.isEmpty ?? true } }
  12. /// Before if name == nil || name.isEmpty else {

    // nil͔ۭͩͬͨΒԿ͔͢Δ } /// After if name.isNilOrEmpty { ... }
  13. ·ͱΊ • nilͱۭ͸ҰॹͰߟ͑Δ৔߹͕ଟ͍ • ஍ຯͳͱ͜ΖͰՄಡੑΛམͱ͞ͳ͍Ұ޻෉ • Objective-C͔ΒSwiftҠߦظʹ͋Δͱศར͔΋

  14. None