Chapter 1
Introduction to SwiftUI

In WWDC 2019, Apple surprised every developer by announcing a completely new framework called SwiftUI. It doesn't just change the way you develop iOS apps. This is the biggest shift in the Apple developer's ecosystem (including iPadOS, macOS, tvOS, and watchOS) since the debut of Swift.

SwiftUI is an innovative, exceptionally simple way to build user interfaces across all Apple platforms with the power of Swift. Build user interfaces for any Apple device using just one set of tools and APIs.

- Apple (https://developer.apple.com/xcode/swiftui/)

Developers have been debating for a long time whether we should use Storyboards or build the app UI programmatically. The introduction of SwiftUI is Apple's answer. With this brand new framework, Apple offers developers a new way to create user interfaces. Take a look at the figure below and have a glance at the code.

Figure 1. Programming in SwiftUI
Figure 1. Programming in SwiftUI

You can now develop the app's UI with a declarative Swift syntax. What that means to you is that the UI code is easier and more natural to write. Compared with the existing UI frameworks like UIKit, you can create the same UI with way less code.

The preview function has always been a weak point of Xcode. While you can preview simple layouts in Interface Builder, you usually can't preview the complete UI until the app is loaded onto the simulators. With SwiftUI and Xcode 11, you get immediate feedback of the UI you are coding. For example, you add a new record to a table, Xcode 11 renders the UI change on the fly in a preview canvas. If you want to preview how your UI looks in dark mode, you just need to change an option. This instant preview feature simply makes UI development a breeze and iteration much faster.

Not only does it allow you to preview the UI, the new canvas also lets you design the user interface visually using drag and drop. What's great is that Xcode automatically generates the SwiftUI code as you add the UI component visually. The code and the UI are always in sync. This is a feature Apple developers anticipated for a long time.

In this book, you will dive deep into SwiftUI, learn how to layout the built-in components, and create complex UIs with the framework. I know some of you may already have experience in iOS development. Let me first walk you through the major differences between the existing framework that you're using (e.g. UIKit) and SwiftUI. If you are completely new to iOS development or even have no programming experience, you can use the information as a reference or even skip the following sections. I don't want to scare away from learning SwiftUI, which is an awesome framework for beginners.

Declarative vs Imperative Programming

Like Java, C++, PHP, and C#, Swift is an imperative programming language since its release. SwiftUI, however, is proudly claimed as a declarative UI framework that lets developers create UI in a declarative way. What does the term "declarative" mean? How does it differ from imperative programming? Most importantly, how does this change affect the way you code?

If you are new to programming, you probably don't need to care the difference because everything is new to you. However, if you have some experience in Object-oriented programming or developed with UIKit before, this paradigm shift affects how you think about building user interface. You may need to unlearn some old concepts and relearn the new ones.

So, what's the difference between imperative and declarative programming? If you go up to Wikipedia and search for the terms, you will find these definitions:

In computer science, imperative programming is a programming paradigm that uses statements that change a program's state. In much the same way that the imperative mood in natural languages expresses commands, an imperative program consists of commands for the computer to perform.

In computer science, declarative programming is a programming paradigm—a style of building the structure and elements of computer programs—that expresses the logic of a computation without describing its control flow.

It's pretty hard to understand the actual difference if you haven't studied Computer Science. Let me explain the difference this way.

Instead of focusing on programming, let's talk about cooking a pizza (or any dishes you like). Assuming you ask your helper to prepare a pizza, you can either do it imperatively or declaratively. To cook the pizza imperatively, you tell your helper each of the instructions clearly like a recipe:

  1. Heat the over to 550°F or higher for at least 30 minutes
  2. Prepare one-pound of dough
  3. Roll out the dough to make a 10-inch circle
  4. Spoon the tomato sauce onto the center of the pizza and spread it out to the edges
  5. Place the toppings (including onions, sliced mushrooms, pepperoni, cooked sausage, cooked bacon, diced peppers) and cheese
  6. Bake the pizza for 5 minutes

On the other hand, if you cook it in a declarative way, you do not need to specify the step by step instructions but just describe how you would like the pizza cooked. Thick or thin crust? Pepperoni and bacon, or just a classic margherita with tomato sauce? 10-inch or 16-inch? The helper will figure out the rest and cook the pizza for you.

That's the core difference between the term imperative and declarative. Now back to UI programming. Imperative UI programming requires developers to write detailed instructions to layout the UI and control its states. Conversely, declarative UI programming lets developers describe how the UI looks like and what you want to do when a state changes.

The declarative way of coding style would make the code more easier to read and understand. Most importantly, the SwiftUI framework allows you to write way less code to create a user interface. Say, for example, you are going to build a heart button in an app. This button should be positioned at the center of the screen and is able to detect touches. If a user taps the heart button, its color is changed from red to yellow. When a user taps and holds the heart, it scales up with an animation.

Figure 2. The implementation of an interactive heart button
Figure 2. The implementation of an interactive heart button

Take a look at figure 2. That's the code you need to implement the heart button. In around 20 lines of code, you create an interactive button with a scale animation. This is power of this declarative UI framework.

No more Interface Builder and Auto Layout

In Xcode 11, you can choose between SwiftUI and Storyboard to build user interface. If you have built an app before, you may use Interface Builder to layout UI on storyboard. With SwiftUI, Interface Builder and storyboards are completely gone. It's replaced by a code editor and a preview canvas like the one shown in figure 2. You write the code in the code editor. Xcode then renders the user interface in real time and display it in the canvas.

Figure 3. User interface option in Xcode 11
Figure 3. User interface option in Xcode 11

Auto layout has always been one of the hard topics when learning iOS development. With SwiftUI, you no longer need to learn how to define a layout constraints and resolve the conflicts. Now you compose the desired UI by using stacks, spacers, and padding. We will discuss this concept in details in later chapters.

The Combine Approach

Other than storyboards, the view controller is gone too. For new comers, you can ignore what a view controller is. But if you are an experienced developer, you may find it strange that SwiftUI doesn't use a view controller as a central building block for talking to the view and the model.

Communications and data sharing between views are now done via another brand new framework called Combine. This new approach completely replaces the role of view controller in UIKit. In this book, we will also cover the basics of Combine and how to use it to handle UI events.

Learn Once, Apply Anywhere

While this book focuses on building UI for iOS, everything you learn here is applicable to other Apple platforms such as watchOS. Prior to the launch of SwiftUI, you'll have to use platform-specific UI frameworks to develop the user interface. You use AppKit to write UI for macOS apps. To develop tvOS apps, you rely on TVUIKit. And, for watchOS apps, you use WatchKit.

With SwiftUI, Apple offers developers a unified UI framework for building user interface on all types of Apple devices. The UI code written for iOS can be easily ported to your watchOS/macOS/watchOS app without modifications or with very minimal modifications. This is made possible thanks to the declarative UI framework.

Your code describes how the user interface looks like. Depending on the platform, the same piece of code in SwiftUI can result in different UI controls. For example, the code below declares a toggle switch:

Toggle(isOn: $isOn) {
    Text("Wifi")
        .font(.system(.title))
        .bold()
}.padding()

For iOS and iPadOS, the toggle is rendered as a switch. On the other hand, SwiftUI renders the control as a checkbox for macOS.

Figure 4. Toggle on macOS and iOS
Figure 4. Toggle on macOS and iOS

The beauty of this unified framework is that you can reuse most of the code on all Apple platforms without making any changes. SwiftUI does the heavy lifting to render the corresponding controls and layout.

However, don't consider SwiftUI as a "Write once, run anywhere" solution. As Apple stressed in a WWDC talk, that's not the goal of SwiftUI. So, don't expect you can turn a beautiful app for iOS into a tvOS app without any modifications.

There are definitely going to be opportunities to share code along the way, just where it makes sense. And so we think it's kind of important to think about SwiftUI less as write once and run anywhere and more like learn once and apply anywhere.

- WWDC Talk (SwiftUI On All Devices)

While the UI code is portable across Apple platforms, you still need to provide specialization that targets for a particular type of device. You should always review each edition of your app to make sure the design is right for the platform. That said, SwiftUI already saves you a lot of time from learning another platform-specific framework, plus you should be able to reuse most of the code.

Interfacing with UIKit/AppKit/WatchKit

Can I use SwiftUI on my existing projects? I don't want to rewrite the entire app which was built on UIKit.

SwiftUI is designed to work with the existing frameworks like UIKit for iOS and AppKit for macOS. Apple provides several representable protocols for you to adopt in order to wrap a view or controller into SwiftUI.

Figure 5. The Representable protocols for existing UI frameworks
Figure 5. The Representable protocols for existing UI frameworks

Say, if you have a custom view developed using UIKit, you can adopt the UIViewRepresentable protocol for that view and make it into SwiftUI. Figure 6 shows the sample code of using MapView in SwiftUI.

Figure 6. Porting MKMapView to SwiftUI
Figure 6. Porting MKMapView to SwiftUI

Use SwiftUI for Your Next Project

Every time when a new framework is released, people usually ask, "Is the framework ready for my next project? Should I wait a little bit longer?"

Though SwiftUI is new to most developers, it's a right time to learn and incorporate the framework in your new project. If you have some personal projects or side projects in your company, there is no reason why you shouldn't try out SwiftUI.

Having that said, you need to consider carefully whether you should apply SwiftUI to your commercial projects. One major drawback of SwiftUI is that it only runs on iOS 13, macOS 10.15, tvOS 13, and watchOS 6. It's very likely your app requires to support lower versions of the platform. In this case, you will have to wait at least a year before adopting SwiftUI.

At the time of this writing, SwiftUI has only been officially released for around a month or two. In terms of features, you can't compare it with the existing UI frameworks (e.g. UIKit), which has been available for years. Some features (e.g. changing the separator style in table views) which are very obvious in the old framework may not be available in SwiftUI. You may need to develop some solutions to work around the issue. This is something you have to take into account when adopting SwiftUI in production projects.

SwiftUI is unarguably very new. It takes time to grow into a mature framework, but what's clear is that SwiftUI is the future of application development for Apple platforms. Even though it may not be applicable to your production projects, it's recommended to start a side project and explore the framework. Once you try out SwiftUI and master the skills, you will enjoy developing UI in a declarative way.

To access the full content and the complete source code, please get your copy at https://www.appcoda.com/swiftui.

results matching ""

    No results matching ""