Mastering MVVM With Swift

Time to Create a View Model

In this episode, we create a view model for the day view controller. Open Cloudy in Xcode and create a new group, View Models, in the Weather View Controllers group. I prefer to keep the view models close to the view controllers in which they're used.

Creating the View Models Group

Create a new Swift file in the View Models group and name it DayViewViewModel.

Creating the Day View View Model

Creating the Day View View Model

Creating the Day View View Model

DayViewViewModel is a struct, a value type. Remember that the view model should keep a reference to the model, which means we need to create a property for it. That's all we need to do to create our first view model.

DayViewViewModel.swift

import Foundation

struct DayViewViewModel {

    // MARK: - Properties

    let weatherData: WeatherData

}

Creating the Public Interface

The next step is moving the code located in the updateWeatherDataContainer(withWeatherData:) method of the DayViewController class to the view model. What we need to focus on are the values we use to populate the user interface.

Date Label

Let's start with the date label. The date label expects a formatted date and it needs to be of type String. It's the responsibility of the view model to ask the model for the value of its time property and transform that value to the format the date label expects.

Let's start by creating a computed property in the view model. We name it date and it should be of type String.

DayViewViewModel.swift

var date: String {

}

We initialize a DateFormatter to convert the date to a formatted string and set the date formatter's dateFormat property. We invoke the date formatter's string(from:) method and return the result. That's it for the date label. This is what the date computed property looks like.

DayViewViewModel.swift

var date: String {
    // Initialize Date Formatter
    let dateFormatter = DateFormatter()

    // Configure Date Formatter
    dateFormatter.dateFormat = "EEE, MMMM d"

    return dateFormatter.string(from: weatherData.time)
}

Time Label

We can repeat this for the time label. We first create a time computed property of type String. The implementation is similar. We create a DateFormatter instance, set its dateFormat property, and return a formatted string.

DayViewViewModel.swift

var time: String {
    // Initialize Date Formatter
    let dateFormatter = DateFormatter()

    // Configure Date Formatter
    dateFormatter.dateFormat = ""

    return dateFormatter.string(from: weatherData.time)
}

There's one complication, though. The format of the time depends on the user's settings in the application. That's easy to solve, though. Navigate to UserDefaults.swift in the Extensions group. We add a computed property, timeFormat, to the TimeNotation enum at the top. The timeFormat computed property returns the correct date format based on the user's preferences. This is what that looks like.

UserDefaults.swift

enum TimeNotation: Int {
    case twelveHour
    case twentyFourHour

    var timeFormat: String {
        switch self {
        case .twelveHour: return "hh:mm a"
        case .twentyFourHour: return "HH:mm"
        }
    }
}

We can now update the implementation of the time computed property like this.

DayViewViewModel.swift

var time: String {
    // Initialize Date Formatter
    let dateFormatter = DateFormatter()

    // Configure Date Formatter
    dateFormatter.dateFormat = UserDefaults.timeNotation().timeFormat

    return dateFormatter.string(from: weatherData.time)
}

Confused? The timeNotation method is a static method of the UserDefaults class. You can find its implementation in UserDefaults.swift. It returns a TimeNotation instance. Take a look at the implementation.

UserDefaults.swift

static func timeNotation() -> TimeNotation {
    let storedValue = UserDefaults.standard.integer(forKey: UserDefaultsKeys.timeNotation)
    return TimeNotation(rawValue: storedValue) ?? TimeNotation.twelveHour
}

We load the user's preference from the user defaults database and use the value to create an instance of the TimeNotation enum. We use the same technique for the user's other preferences.

Description Label

Populating the description label is easy. We define a computed property in the view model, summary, of type String and we return the value of the summary property of the model.

DayViewViewModel.swift

var summary: String {
    return weatherData.summary
}

Temperature Label

The value for the temperature label is a bit more complicated because we need to take the user's preferences into account. We start simple. We create another computed property in which we store the temperature in a constant, temperature.

DayViewViewModel.swift

var temperature: String {
    let temperature = weatherData.temperature
}

We fetch the user's preference and format the value stored in the temperature constant based on the user's preference. Notice that we need to convert the temperature if the user's preference is set to degrees Celcius.

DayViewViewModel.swift

var temperature: String {
    let temperature = weatherData.temperature

    switch UserDefaults.temperatureNotation() {
    case .fahrenheit:
        return String(format: "%.1f °F", temperature)
    case .celsius:
        return String(format: "%.1f °C", temperature.toCelcius())
    }
}

The implementation of the temperatureNotation() static method is very similar to the timeNotation() static method we looked at earlier.

UserDefaults.swift

static func temperatureNotation() -> TemperatureNotation {
    let storedValue = UserDefaults.standard.integer(forKey: UserDefaultsKeys.temperatureNotation)
    return TemperatureNotation(rawValue: storedValue) ?? TemperatureNotation.fahrenheit
}

Wind Speed Label

Populating the wind speed label is very similar. Because the wind speed label expects a string, we create a windSpeed computed property of type String. We ask the model for the the value of its windSpeed property and format that value based on the user's preference.

DayViewViewModel.swift

var windSpeed: String {
    let windSpeed = weatherData.windSpeed

    switch UserDefaults.unitsNotation() {
    case .imperial:
        return String(format: "%.f MPH", windSpeed)
    case .metric:
        return String(format: "%.f KPH", windSpeed.toKPH())
    }
}

The implementation of the unitsNotation() static method is very similar to the timeNotation() and temperatureNotation() static methods we looked at earlier.

UserDefaults.swift

static func unitsNotation() -> UnitsNotation {
    let storedValue = UserDefaults.standard.integer(forKey: UserDefaultsKeys.unitsNotation)
    return UnitsNotation(rawValue: storedValue) ?? UnitsNotation.imperial
}

Icon Image View

For the icon image view, we need an image. We could put this logic in the view model. However, because we need the same logic later, in the view model of the week view controller, it's better to create an extension for UIImage in which we put that logic.

Create a new file in the Extensions group and name it UIImage.swift. Create an extension for the UIImage class and define a class method imageForIcon(withName:).

UIImage.swift

import UIKit

extension UIImage {

    class func imageForIcon(withName name: String) -> UIImage? {

    }

}

We simplify the current implementation of the weather view controller. We use the value of the name argument to instantiate the UIImage instance in most cases of the switch statement. I really like how flexible the switch statement is in Swift.

UIImage.swift

import UIKit

extension UIImage {

    class func imageForIcon(withName name: String) -> UIImage? {
        switch name {
        case "clear-day", "clear-night", "rain", "snow", "sleet": return UIImage(named: name)
        case "wind", "cloudy", "partly-cloudy-day", "partly-cloudy-night": return UIImage(named: "cloudy")
        default: return UIImage(named: "clear-day")
        }
    }

}

Notice that we also return a UIImage instance in the default case of the switch statement.

With this method in place, it's very easy to populate the icon image view. We create a computed property of type UIImage? in the view model and name it image. In the body of the computed property, we invoke the class method we just created, passing in the value of the model's icon property.

DayViewViewModel.swift

var image: UIImage? {
    return UIImage.imageForIcon(withName: weatherData.icon)
}

Because UIImage is defined in the UIKit framework, we need to replace the import statement for Foundation with an import statement for UIKit.

DayViewViewModel.swift

import UIKit

struct DayViewViewModel {

    ...

}

This is a code smell. Whenever you import UIKit in a view model, a warning bell should go off. The view model shouldn't need to know anything about views or the user interface. In this example, however, we have no other option. Since we want to return a UIImage instance, we need to import UIKit. If you don't like this, you can also return the name of the image and have the view controller be in charge of creating the UIImage instance. That's up to you.

We're almost done. I want to make two small improvements. The DateFormatter instance shouldn't be created in the computed properties in my opinion. We can create private properties for those.

DayViewViewModel.swift

import UIKit

struct DayViewViewModel {

    // MARK: - Properties

    let weatherData: WeatherData

    // MARK: -

    private let dateFormatter = DateFormatter()
    private let timeFormatter = DateFormatter()

    // MARK: -

    var date: String {
        // Configure Date Formatter
        dateFormatter.dateFormat = "EEE, MMMM d"

        return dateFormatter.string(from: weatherData.time)
    }

    var time: String {
        // Configure Date Formatter
        timeFormatter.dateFormat = UserDefaults.timeNotation().timeFormat

        return timeFormatter.string(from: weatherData.time)
    }

    ...

}

I've chosen to create a separate date formatter for the date and time properties. You could use the same date formatter for both properties and only update the date formatter's dateFormat property. It's up to you to decide which option you prefer.

Great. We've created our first view model. In the next episode, we put it to use in the day view controller.

Next Episode "Put the View Model to Work"

Stop Writing Swift That Sucks

Download the Swift Patterns I Swear By