Building a Weather watchOS app (Part 2) — Understanding MVVM pattern Swift

Jany Mai
3 min readMay 13, 2020

--

Hi guys, I’m Jany

Today, I continue share about the topic How can I apply MVVM pattern in my weather watchOS.

If you are watching my video, I will happy if you guys give me a 1 subscriber. Thanks so much

MVVM stands for Model View ViewModel. Design Patterns are platform-independent. This means you can use design patterns with any language.

I will use weather watchOS to explain MVVM pattern

First of all, I will talk about the View.

View

This is the View. What we need here:

  • Temp
  • Country Name
  • Country Flag

What user can see, that mean this is the View

Now let analysis:

Users can see temp but temp always changes so we need to get Temp data from service, right?

The main screen will show the country is Singapore and Singapore national flag.

Model

Model Identify objects

For this screen we need to have 2 for Models:

Country

country: {
name: "Singapore",
flag: "singapore"
}

Weather

weather: {
temp: 30.2
}

If you define the object type for data sending out or returning to app users need to define with type. Let say:

You call a GET api and you get data return from the server-side. For this point, we should declare with type Decodable

Decodable A type that can decode itself from an external representation.

struct Weather: Decodable {
var temp: Double?
}

You call a POST api and you will send data to the server to create one more country. For this point, we should declare with type Codable

Codable A type that can convert itself into and out of an external representation.

struct Country: Codable {
let name: String
let flag: String
}

View Model

We need to get the country’s weather from service. When data return to base on the struct you defined in Model you can know that is correct data or not.

The ViewModel is the place that helps you handle, prepare data before you send it back to View to render and show to the user. When the View models update data, it is automatically updated in the View and vice versa

View models represent the data and the structure behind the view.

For Beginner when I talk about service it mean you will get data from service by calling API

Alright, ^___^

That’s all for this blog. See you in the next blog “Make UI and get data from the server for Weather Screen” (Calling API in Swift) in my series “Building a Weather watchOS app with SwiftUI”.

Read my blogs in series “Building a weather watchOS app with SwiftUI”

--

--