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. Objective-C if (users.count == 0) { // nil͔ۭͩͬͨΒԿ͔͢Δ } if

    (name.length == 0) { // ໊લ͕nil͔ۭͩͬͨΒԿ͔͢Δ }
  2. 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 } }
  3. 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 } }
  4. /// Before if name == nil || name.isEmpty else {

    // nil͔ۭͩͬͨΒԿ͔͢Δ } /// After if name.isNilOrEmpty { ... }