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

Swift Optional Extension Tips

horimislime
August 17, 2016

Swift Optional Extension Tips

horimislime

August 17, 2016
Tweet

More Decks by horimislime

Other Decks in Technology

Transcript

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

    View full-size slide

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

    View full-size slide

  3. Optionalͷ஍ຯͳπϥΈ

    View full-size slide

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

    View full-size slide

  5. Swift
    // Compile error !
    if users?.isEmpty {
    // ...
    }
    if name?.isEmpty {
    // ...
    }

    View full-size slide

  6. OptionalΛѻ͏ࡍͷ͓໿ଋ
    guard let users = users where !users.isEmpty else {
    // nil͔ۭͩͬͨΒԿ͔͢Δ
    }

    View full-size slide

  7. Nil Coalescing
    • ୹͘ॻ͚Δ͕ɺͺͬͱݟͷՄಡੑʹ͚ܽΔ
    if array?.isEmpty ?? false {
    // ...
    }
    if !(str ?? "").isEmpty {
    // ...
    }

    View full-size slide

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

    View full-size slide

  9. ໰୊
    • ܕ͕ݫີʹͳͬͨ΋ͷͷɺʮۭʯͷѻ͍͕໘౗
    • nilͱۭͷঢ়ଶΛಉ͡Α͏ʹѻ͏ʹ͸ʁ

    View full-size slide

  10. Optional Extension
    • isNilOrEmptyతͳ΋ͷ
    • ௚઀Optionalʹextension͸ੜ΍ͤͳ͍
    // Error: 'Wrapped' constrained to non-protocol type 'String'
    extension Optional where Wrapped: String {
    var isNilOrEmpty: Bool {
    return self?.isEmpty ?? true
    }
    }

    View full-size slide

  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
    }
    }

    View full-size slide

  12. /// Before
    if name == nil || name.isEmpty else {
    // nil͔ۭͩͬͨΒԿ͔͢Δ
    }
    /// After
    if name.isNilOrEmpty {
    ...
    }

    View full-size slide

  13. ·ͱΊ
    • nilͱۭ͸ҰॹͰߟ͑Δ৔߹͕ଟ͍
    • ஍ຯͳͱ͜ΖͰՄಡੑΛམͱ͞ͳ͍Ұ޻෉
    • Objective-C͔ΒSwiftҠߦظʹ͋Δͱศར͔΋

    View full-size slide