SlideShare a Scribd company logo
1 of 55
Download to read offline
POMVVM@NATASHATHEROBOT
"Swift Is a Protocol-Oriented
Programming Language"
— Dave Abrahams, Professor of Blowing-Your-Mind
UITableViewDelegate
UITableViewDataSource
UITextFieldDelegate
NSURLSessionDelegate
CLLocationManagerDelegate
MCSessionDelegate
!
!
!
!
Artsy Engineering: MVVM in Swift
MODEL
let amount = 6729383.99
VIEW
Your balance is $6,729,383.99
VIEWMODEL
struct AccountViewModel {
let displayBalance: String
init(model: BankAccount) {
let formattedBalance = model.balance.currencyValue
displayBalance = "Your balance is (formattedBalance)"
}
}
VIEWCONTROLLER
var viewModel = ViewModel(model: Account)
VIEWCONTROLLER
var viewModel = ViewModel(model: Account)
PROTOCOLS
!!!
THE PROBLEM
class SwitchWithTextTableViewCell: UITableViewCell {
func configure(
title: String,
titleFont: UIFont,
titleColor: UIColor,
switchOn: Bool,
switchColor: UIColor = .purpleColor(),
onSwitchToggleHandler: onSwitchToggleHandlerType? = nil)
{
// configure views here
}
}
PROTOCOLS TO
THE RESCUE !
protocol SwitchWithTextCellProtocol {
var title: String { get }
var titleFont: UIFont { get }
var titleColor: UIColor { get }
var switchOn: Bool { get }
var switchColor: UIColor { get }
func onSwitchTogleOn(on: Bool)
}
extension SwitchWithTextCellProtocol {
var switchColor: UIColor {
return .purpleColor()
}
}
class SwitchWithTextTableViewCell: UITableViewCell {
func configure(withDelegate delegate: SwitchWithTextCellProtocol)
{
// configure views here
}
}
struct MinionModeViewModel: SwitchWithTextCellProtocol {
var title = "Minion Mode!!!"
var switchOn = true
var switchColor: UIColor {
return .yellowColor()
}
func onSwitchTogleOn(on: Bool) {
if on {
print("The Minions are here to stay!")
} else {
print("The Minions went out to play!")
}
}
}
CELLFORROWATINDEXPATH
// YourViewController.swift
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchWithTextTableViewCell",
forIndexPath: indexPath) as! SwitchWithTextTableViewCell
// this is where the magic happens!
cell.configure(withDelegate: MinionModeViewModel())
return cell
!
✍
protocol SwitchWithTextCellDataSource {
var title: String { get }
var switchOn: Bool { get }
}
protocol SwitchWithTextCellDelegate {
func onSwitchTogleOn(on: Bool)
var switchColor: UIColor { get }
var textColor: UIColor { get }
var font: UIFont { get }
}
// SwitchWithTextTableViewCell
func configure(withDataSource dataSource: SwitchWithTextCellDataSource,
delegate: SwitchWithTextCellDelegate?)
{
// configure views here
}
struct MinionModeViewModel: SwitchWithTextCellDataSource {
var title = "Minion Mode!!!"
var switchOn = true
}
extension MinionModeViewModel: SwitchWithTextCellDelegate {
var switchColor: UIColor {
return .yellowColor()
}
func onSwitchTogleOn(on: Bool) {
if on {
print("The Minions are here to stay!")
} else {
print("The Minions went out to play!")
}
}
}
// SettingsViewController
let viewModel = MinionModeViewModel()
cell.configure(withDataSource: viewModel, delegate: viewModel)
return cell
!
@MHOLLEMANS: MIXINS
AND TRAITS IN SWIFT 2.0
class AIPlayer: GameObject, AITrait, GunTrait, RenderTrait, HealthTrait {
...
}
class ZapMonster: GameObject, GunTrait, RenderTrait, HealthTrait, MovementTrait {
...
}
! "
protocol TextPresentable {
var text: String { get }
var textColor: UIColor { get }
var font: UIFont { get }
}
protocol SwitchPresentable {
var switchOn: Bool { get }
var switchColor: UIColor { get }
func onSwitchTogleOn(on: Bool)
}
protocol ImagePresentable {
var imageName: String { get }
}
protocol TextFieldPresentable {
var placeholder: String { get }
var text: String { get }
func onTextFieldDidEndEditing(textField: UITextField)
}
extension TextPresentable {
var textColor: UIColor {
return .blackColor()
}
var font: UIFont {
return .systemFontOfSize(17)
}
}
!!!
class SwitchWithTextTableViewCell<T where T: TextPresentable, T: SwitchPresentable>: UITableViewCell {
private var delegate: T?
func configure(withDelegate delegate: T) {
// configure views here
}
}
extension MinionModeViewModel: TextPresentable {
var text: String { return "Minion Mode" }
var textColor: UIColor { return .blackColor() }
var font: UIFont { return .systemFontOfSize(17.0) }
}
extension MinionModeViewModel: SwitchPresentable {
var switchOn: Bool { return false }
var switchColor: UIColor { return .yellowColor() }
func onSwitchTogleOn(on: Bool) {
if on {
print("The Minions are here to stay!")
} else {
print("The Minions went out to play!")
}
}
}
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchWithTextTableViewCell",
forIndexPath: indexPath) as! SwitchWithTextTableViewCell<MinionModeViewModel>
let viewModel = MinionModeViewModel()
cell.configure(withDelegate: viewModel)
return cell
!"#
"Change is the only constant."
— Unknown
class SwitchWithTextTableViewCell<T where T: TextPresentable, T: SwitchPresentable, T: ImagePresentable>: UITableViewCell {
}
extension MinionModeViewModel: ImagePresentable {
var imageName: String { return "minionParty.png" }
}
!"
> Use Protocols to Configure Your Views
> Use Protocol Extensions for Defaults
> Use ViewModels to Provide Data for the Protocols
HOW CAN WE
MAKE THIS
BETTER?

More Related Content

What's hot

What's hot (19)

Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testing
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
 
Everything You (N)ever Wanted to Know about Testing View Controllers
Everything You (N)ever Wanted to Know about Testing View ControllersEverything You (N)ever Wanted to Know about Testing View Controllers
Everything You (N)ever Wanted to Know about Testing View Controllers
 
Workshop 8: Templating: Handlebars, DustJS
Workshop 8: Templating: Handlebars, DustJSWorkshop 8: Templating: Handlebars, DustJS
Workshop 8: Templating: Handlebars, DustJS
 
(국비지원학원/재직자교육/실업자교육/IT실무교육_탑크리에듀)#4.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)
(국비지원학원/재직자교육/실업자교육/IT실무교육_탑크리에듀)#4.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)(국비지원학원/재직자교육/실업자교육/IT실무교육_탑크리에듀)#4.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)
(국비지원학원/재직자교육/실업자교육/IT실무교육_탑크리에듀)#4.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)
 
Anonymous functions in JavaScript
Anonymous functions in JavaScriptAnonymous functions in JavaScript
Anonymous functions in JavaScript
 
Viking academy backbone.js
Viking academy  backbone.jsViking academy  backbone.js
Viking academy backbone.js
 
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
 
Rails on Oracle 2011
Rails on Oracle 2011Rails on Oracle 2011
Rails on Oracle 2011
 
Integrating React.js with PHP projects
Integrating React.js with PHP projectsIntegrating React.js with PHP projects
Integrating React.js with PHP projects
 
Auto-GWT : Better GWT Programming with Xtend
Auto-GWT : Better GWT Programming with XtendAuto-GWT : Better GWT Programming with Xtend
Auto-GWT : Better GWT Programming with Xtend
 
Vue next
Vue nextVue next
Vue next
 
Gwt and Xtend
Gwt and XtendGwt and Xtend
Gwt and Xtend
 
Why Every Tester Should Learn Ruby
Why Every Tester Should Learn RubyWhy Every Tester Should Learn Ruby
Why Every Tester Should Learn Ruby
 
Why ruby
Why rubyWhy ruby
Why ruby
 
Frontin like-a-backer
Frontin like-a-backerFrontin like-a-backer
Frontin like-a-backer
 
Backbone js
Backbone jsBackbone js
Backbone js
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 
React, Redux and es6/7
React, Redux and es6/7React, Redux and es6/7
React, Redux and es6/7
 

Similar to Protocol-Oriented MVVM (extended edition)

Similar to Protocol-Oriented MVVM (extended edition) (20)

Building mobile web apps with Mobello
Building mobile web apps with MobelloBuilding mobile web apps with Mobello
Building mobile web apps with Mobello
 
[22]Efficient and Testable MVVM pattern
[22]Efficient and Testable MVVM pattern[22]Efficient and Testable MVVM pattern
[22]Efficient and Testable MVVM pattern
 
Asp.NET MVC
Asp.NET MVCAsp.NET MVC
Asp.NET MVC
 
Knockout.js
Knockout.jsKnockout.js
Knockout.js
 
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller PatternDeveloping ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
 
Migrating Objective-C to Swift
Migrating Objective-C to SwiftMigrating Objective-C to Swift
Migrating Objective-C to Swift
 
Swift - One step forward from Obj-C
Swift -  One step forward from Obj-CSwift -  One step forward from Obj-C
Swift - One step forward from Obj-C
 
Intro to Laravel 4
Intro to Laravel 4Intro to Laravel 4
Intro to Laravel 4
 
Integrating SAP the Java EE Way - JBoss One Day talk 2012
Integrating SAP the Java EE Way - JBoss One Day talk 2012Integrating SAP the Java EE Way - JBoss One Day talk 2012
Integrating SAP the Java EE Way - JBoss One Day talk 2012
 
Asp.net mvc training
Asp.net mvc trainingAsp.net mvc training
Asp.net mvc training
 
Wt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technologyWt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technology
 
Wt unit 2 ppts client side technology
Wt unit 2 ppts client side technologyWt unit 2 ppts client side technology
Wt unit 2 ppts client side technology
 
Sqlapi0.1
Sqlapi0.1Sqlapi0.1
Sqlapi0.1
 
Say bye to Fragments with Conductor & Kotlin
Say bye to Fragments with Conductor & KotlinSay bye to Fragments with Conductor & Kotlin
Say bye to Fragments with Conductor & Kotlin
 
Fundaments of Knockout js
Fundaments of Knockout jsFundaments of Knockout js
Fundaments of Knockout js
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVC
 
Red Hat Agile integration Workshop Labs
Red Hat Agile integration Workshop LabsRed Hat Agile integration Workshop Labs
Red Hat Agile integration Workshop Labs
 
DataFX 8 (JavaOne 2014)
DataFX 8 (JavaOne 2014)DataFX 8 (JavaOne 2014)
DataFX 8 (JavaOne 2014)
 
Patterns Are Good For Managers
Patterns Are Good For ManagersPatterns Are Good For Managers
Patterns Are Good For Managers
 
Jsf intro
Jsf introJsf intro
Jsf intro
 

More from Natasha Murashev

More from Natasha Murashev (20)

Digital Nomad: The New Normal
Digital Nomad: The New NormalDigital Nomad: The New Normal
Digital Nomad: The New Normal
 
Build Features, Not Apps
Build Features, Not AppsBuild Features, Not Apps
Build Features, Not Apps
 
Build Features Not Apps
Build Features Not AppsBuild Features Not Apps
Build Features Not Apps
 
Build Features Not Apps
Build Features Not AppsBuild Features Not Apps
Build Features Not Apps
 
The Secret Life of a Digital Nomad
The Secret Life of a Digital NomadThe Secret Life of a Digital Nomad
The Secret Life of a Digital Nomad
 
How to Win on the Apple Watch
How to Win on the Apple WatchHow to Win on the Apple Watch
How to Win on the Apple Watch
 
Hello watchOS2
Hello watchOS2 Hello watchOS2
Hello watchOS2
 
The Swift Architect
The Swift ArchitectThe Swift Architect
The Swift Architect
 
The Zen Guide to WatchOS 2
The Zen Guide to WatchOS 2The Zen Guide to WatchOS 2
The Zen Guide to WatchOS 2
 
HealthKit Deep Dive
HealthKit Deep DiveHealthKit Deep Dive
HealthKit Deep Dive
 
Using Parse in Hackathons
Using Parse in HackathonsUsing Parse in Hackathons
Using Parse in Hackathons
 
Hello, WatchKit
Hello, WatchKitHello, WatchKit
Hello, WatchKit
 
Hello, WatchKit
Hello, WatchKitHello, WatchKit
Hello, WatchKit
 
Unleash the Power of Playgrounds
Unleash the Power of PlaygroundsUnleash the Power of Playgrounds
Unleash the Power of Playgrounds
 
Hello, WatchKit
Hello, WatchKitHello, WatchKit
Hello, WatchKit
 
AltConf 2015: Swift Thinking
AltConf 2015: Swift ThinkingAltConf 2015: Swift Thinking
AltConf 2015: Swift Thinking
 
Swift Thinking
Swift ThinkingSwift Thinking
Swift Thinking
 
Funcitonal Swift Conference: The Functional Way
Funcitonal Swift Conference: The Functional WayFuncitonal Swift Conference: The Functional Way
Funcitonal Swift Conference: The Functional Way
 
Intro To Swift
Intro To SwiftIntro To Swift
Intro To Swift
 
HealthKit: Getting Ready for the New Year
HealthKit: Getting Ready for the New YearHealthKit: Getting Ready for the New Year
HealthKit: Getting Ready for the New Year
 

Recently uploaded

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 

Protocol-Oriented MVVM (extended edition)