Introduction to MVVM

With Swift



Gil Shapira

iOS + Android

web: gil.sh
github: shilgapira

Agenda

Quick intro

Swift

Demo

MVVM



Model • View • ViewModel

Data
Presentation
Behavior

So...... MVC?

Problem

Massive View Controller

Problem

Hard to unit test

Problem

Hard to reuse code

Problem

Platform Specific



Model: Data Layer

Entities

Persistence

Network

Example

User Model



struct User {
    // 10374498
    let id: Int64
    
    // "John"
    let firstName: String
    
    // "Appleseed"
    let lastName: String
    
    // From unix timestamp perhaps
    let birthday: NSDate?
    
    // URL of an image
    let pictureURL: String?
    
    // Coordinates of user's home
    let home: CLLocation?
}
						


ViewModel: Behavior Layer

Value Transformations

View State

Input Validation

Operations and Actions

Example

User ViewModel



class UserViewModel {
    // "John A."
    var name: String
    
    // "In 12 days", "In August", "Unknown"
    var birthday: String
    
    // "8 miles away", "New York", "Unknown"
    var distanceToHome: String
    
    // .Network provides a URL for a remote image,
    // .Placeholder provides initials of user's name and background fill color
    var picture: Picture
    
    enum Picture {
        case Network(NSURL)
        case Placeholder(String, UInt64)
    }
    
    // ... implementation ...
}
						


View: Presentation Layer

User Interface

Data Updates

Events

Example

User View


User View


Profit

Separation of Concerns

Unit Testing

Code Reuse

iOS / OS X

Swift

Win

Less files

Win

Inner classes

Win

Value types

Win

Modern syntax

Frameworks

Multiple Targets

iOS / OS X

Unit Test

Without Simulator

Demo

github.com/shilgapira/SwiftDemoMVVM

Thanks!


Turns

turns.launchrock.com