SwiftUi With Combine Part 1

Kushal Dave
4 min readOct 9, 2019

--

If you are an iOS developer you would probably have heard about SwiftUi which was announced in Apple WWDC19 as an innovative, exceptionally simple way to build user interfaces across all Apple platforms with the power of Swift. At the same time Apple also announced Combine which customizes handling of asynchronous events by combining event-processing operators.

For those who are aware about SwiftUi and Combine can skip the next 2 paragraphs and get started with coding

SwiftUi

SwiftUi is new Framework by apple to replace Storyboard for creating user Interface , it is declarative framework with SwiftUI, you can define what your app’s UI should do with concise, declarative language, and with minimum code

Combine

Combine works same as rxSwift or ReactiveSwift as it is a part of reactive programing It allows you to write functional reactive code by providing a declarative Swift API. you can read more about it here

What are we going to build

Using SwiftUi and Combine we will build a single screen app that will displays list of users , the end result will look like this

Dependencies

System Requirements

  • xCode 11
  • macOS 10.15+ (if you want live preview , you can work without it by running the app on simulator or device)

Lets get started with Phase 1 (creating a list local data)

  • Create a new project and make sure SwiftUi is selected in user Interface
  • Create a UserModel.swift file , extend the class with Identifiable and assign an var named id to UUID() this will create an unique id for each object for our list to identify , also add name , email , phoneNum and imageUrl as Strings… the class would look like this
import Foundationpublic struct UserModel :Identifiable {public var id = UUID()let name,email,phoneNum,imageUrl:String}
  • With our model class created we can start working on ui but before adding views lets add the kingfisher library to display images from url
To add the dependency go to File -> Swift Packages -> add Package Dependencythen enter “ https://github.com/onevcat/Kingfisher.git “ in the textboxthen select KingfisherSwiftUi and click finish(if you run into any error you can check the Installation guide here)
  • Now lets create an contentItemView file where we will declare ui for items of our list , it would contain one image and 3 texts
  • In the file make sure you import SwiftUI and KingfisherSwiftUI
  • Add “ @State var user: UserModel ” it will take usermodel as parameter for the class

We will need to use following elements to create our view

KFImage :- from kingfisher library , it will load image from urlVStack and HStack :- these two are viewContainers , they will stack views in vertical and horizontal respectivelyText :- it will create a textview with the text passed in as argumentSpacer() :- it will add space between views

Using these we will create item view for list , the class will look like

import Foundationimport SwiftUIimport KingfisherSwiftUIstruct ContentItemView : View {@State var user: UserModelvar body: some View {HStack {KFImage(URL(string: (self.user.imageUrl))!).resizable().clipShape(Circle()).frame(width: 70, height: 70)VStack(alignment: .leading) {Text(user.name)Spacer()Text(user.email)Spacer()Text(user.phoneNum)Spacer()}.padding(.init(top: 2, leading: 8, bottom: 2, trailing: 8)) //adds padding}.padding(.init(top: 10, leading: 0, bottom: 10, trailing: 0))}}
  • Now that we have all the components we need lets put everything together and get the app running
  • Go to contentView.swift file
  • In this file create a list of UserModel objects and add dummy data to it
  • In body add list with users in navigation view and call contentItemView for each user
  • The final class should look like this
import SwiftUIstruct ContentView: View {//declared a static list of users herelet users = [UserModel(name: “person 1”, email: “person1@gmail.com”,phoneNum: “678359234”, imageUrl: “https://icon-library.net/images/user-image-icon/user-image-icon-17.jpg"),UserModel(name: “person 2”, email: “person1@gmail.com”,phoneNum: “732874936”, imageUrl: “https://static.thenounproject.com/png/17241-200.png"),UserModel(name: “person 3”, email: “person1@gmail.com”,phoneNum: “268395975”, imageUrl: “https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQYm-KcyvHy3PDkmh0V9KzkUk26255h0RwthshiaoanTnfH2B_IRg")]var body: some View {NavigationView{List(users) { user in //will create views for every user in our listContentItemView(user: user) //we send each user object to the itemview class which will create view with the object}.navigationBarTitle(Text(“Users”)) //adds navigation title}}}struct ContentView_Previews: PreviewProvider {static var previews: some View {ContentView()}}
  • Now with this phase 1 is done you can run the app and will see the list of users
  • Do play a little with the code and try different variations in design

Bonus Tip

  • In content view instead of adding users directly in list you can use for loop for more flexibility and control , it is not necessary for our task but if we wanted to do it using for loop the code would be as follow
List{Text(“Users”).font(.largeTitle).bold() //creates a textview with title users with large fonts in boldForEach(users) { user inContentItemView(user: user)}}

In the next part we will get data by api from viewmodel using combine

Thank you for reading! Feel free to say hi or share your thoughts on Twitter @that_kushal_guy or in the responses below!

You can checkout the full project source code here

--

--