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

Design patterns in Swift Vol. 0

Johnlin
December 13, 2016

Design patterns in Swift Vol. 0

Johnlin

December 13, 2016
Tweet

More Decks by Johnlin

Other Decks in Programming

Transcript

  1. ࠷ஶ໊తઃܭ໛ࣜ၇ • Design Patterns: Elements of Reusable Object-Oriented Software 


    BY Erich Gamma , Richard Helm , Ralph Johnson , John Vlissides ؆᜝ GoF(gang of four) ࢛ਓ㢨ɻ • ཫ໘ሜྃ23 छৗݟతC++෺݅ಋ޲໛ ࣜɻ
  2. @interface Singleton : NSObject @end @implementation Singleton + (instancetype)sharedInstance {

    static Singleton *sharedInstance = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedInstance = [[Singleton alloc] init]; }); return sharedInstance; } @end
  3. error: 'dispatch_once_t' is unavailable in Swift: Use lazily initialized globals

    instead static var onceToken: dispatch_once_t = 0 ^~~~~~~~~~~~~~~
  4. for i in 1...10 { print(i) } for c in

    "hello world".characters { print(c) }
  5. Swift తభ୅ث Protocol
 IteratorProtocol • ੋҰݸ Protocol • ୞༗ҰݸඞཁతവᏐ next()

    • ᙛ༗ԼҰݸݩૉ࣌ɼճၚಹݸݩૉ • ᔒ༗ԼҰݸݩૉత࣌ީɼճၚ nil
  6. var s = "" let iter = AnyIterator<String> { let

    c = s.characters.count % 2 == 0 ? "5" : "6" s = s + c return s.characters.count > 10 ? nil : s } for c in iter { print(c) } /* 5 56 … 565656565 5656565656 */
  7. var s = "" let iter = AnyIterator<String> { let

    c = s.characters.count % 2 == 0 ? "5" : "6" s = s + c return s.characters.count > 10 ? nil : s } for c in iter.filter({ $0.characters.count % 2 == 0 }) { print(c) } /* 56 5656 565656 56565656 5656565656 */
  8. var s = "" let iter = AnyIterator<String> { let

    c = s.characters.count % 2 == 0 ? "5" : "6" s = s + c return s.characters.count > 10 ? nil : s } for (idx,c) in iter.enumerated() { print("\(idx):\(c)") } /* 0:5 1:56 2:565 … 8:565656565 9:5656565656 */
  9. class PPAP : Sequence, IteratorProtocol { typealias Element = String

    let stuffs = [ "APPLEPEN", "PINEAPPLEPEN", "PENPINEAPPLEAPPLEPEN"] var idx = 0 func next()-> String? { defer {idx += 1} guard idx < stuffs.count else { return nil } return stuffs[idx] } } let ppap = PPAP() for p in ppap { print(p) }
  10. class PPAP : Sequence, IteratorProtocol { typealias Element = String

    let stuffs = [ "APPLEPEN", "PINEAPPLEPEN", "PENPINEAPPLEAPPLEPEN"] var idx = 0 func next()-> String? { defer {idx += 1} guard idx < stuffs.count else { return nil } return stuffs[idx] } } let ppap = PPAP() for p in ppap { print(p) } /* APPLEPEN PINEAPPLEPEN PENPINEAPPLEAPPLEPEN */
  11. Q&A