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

MVVMでProtocol Oriented をやってみた話

kumapo
November 29, 2016

MVVMでProtocol Oriented をやってみた話

#potatotips 35 の発表資料です

kumapo

November 29, 2016
Tweet

Other Decks in Technology

Transcript

  1. ͖ΐ͏࿩͢͜ͱ • αΠυϓϩδΣΫτͰॳΊͯMVVMΛ࠾༻ͯ͠Ҏདྷɺ ઃܭΛࢼߦࡨޡ͖ͯͨ͠ • ͖ΐ͏͸ ViewModelͰ Protocol Oriented ΍ͬͯΈ

    ͨ࿩Λ͠·͢ • Ξϓϩʔνͱͯ͠͸ ”Introduction to Protocol- Oriented MVVM by Natasha Murashev” ΛΞϨϯδ
  2. MVVM Ͱࢼߦࡨޡͨ͠Օॴ • ViewModel Ͱͷ Data Formatting • σʔλʢModelͳͲʣ Λ

    View͕ٻΊΔܗ΁ ͱม׵͢ΔՕॴ • ViewModel ಉ࢜Ͱ ϩδοΫ͕ॏෳͯ͠͠· ͏
  3. // ImageView΁σʔλΛఏڙ͢ΔViewModel struct ShowStickerViewModel { var model: Sticker var imageURL:

    URL? { return URL(string: model.imageURLString) } var placeholderImage: UIImage { return UIImage(named: “imgBlank”)! } Before: Data Formatting // TableViewCellͷImageView΁σʔλΛఏڙ͢ΔViewModel struct StickerCellViewModel { var model: Sticker var imageURL: URL? { return URL(string: model.imageURLString) } var placeholderImage: UIImage { return UIImage(named: “imgBlank”)! }
  4. // Protocol Extension ͯ͠ ImageURLPresentable ͷϓϩύςΟΛ࣮૷ // ܕ੍໿ͱͯ͠ Sticker Λࢦఆ

    extension ViewModelType where Self: ImageURLPresentable, ModelType == Sticker { // σϑΥϧτͷ࣮૷: Sticker Λ Data Formatting ͢Δ var imageURL: URL? { return URL(string: model.imageURLString)ɹ } var placeholderImage: UIImage { return UIImage(named: “imgBlank”)! } After: Data Formatting // σʔλϑΥʔϚοτͷσϑΥϧτͷ࣮૷Λఏڙ͢Δϓϩτίϧ protocol ViewModelType { associatedtype ModelType // ϑΥʔϚοτର৅ͷܕΛύϥϝʔλʔʹ var model: ModelType { get } }
  5. struct ShowStickerViewModel: ViewModelType { typealias ModelType = Sticker var model:

    ModelType } extension ShowStickerViewModel: ImageURLPresentable {} // ϓϩτίϧʹద߹ After: Data Formatting struct StickerCellViewModel: ViewModelType { typealias ModelType = Sticker var model: ModelType } extension StickerCellViewModel: ImageURLPresentable {} // ϓϩτίϧʹద߹ // ShowStickerViewController.swift imageView!.sd_setImage(with: viewModel.imageURL, placeholderImage: viewModel.placeholderImage)
  6. ·ͱΊ • ViewModel ͷ Data Formatting ͷ ϩδοΫΛ Protocol Extension

    Λ༻͍ͯڞ௨Խͨ͠ • ViewModel ΛܕύϥϝʔλʔΛ࣋ͭϓϩτίϧʹద ߹ͤ͞Δ • Protocol Extension Λ༻͍ͯ Data Formattingͷσ ϑΥϧτ࣮૷Λఏڙ͢Δ • σϑΥϧτͷ࣮૷͸ର৅ͷσʔλΛܕ੍໿ʹ͓ͯ͘͠