Learn SwiftUI

5 (1 reviews total)
By Chris Barker
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Getting Started with SwiftUI

About this book

SwiftUI is the new and powerful interface toolkit that lets you design and build iOS, iPadOS, and macOS apps using declarative syntax. It is a powerful way to develop the UI elements of applications, which would normally be tightly coupled to application logic.

Learn SwiftUI will get you up to speed with the framework and cross-device UI development in no time. Complete with detailed explanations and practical examples, this easy-to-follow guide will teach you the fundamentals of the SwiftUI toolkit. You'll learn how to build a powerful iOS and iPadOS application that can be reused for deployment on watchOS. As you progress, you'll delve into UI and unit testing in iOS apps, along with learning how to test your SwiftUI code for multiple devices. The book will also show you how to integrate SwiftUI features such as data binding and network requests into your current application logic.

By the end of this book, you will have learned how to build a cross-device application using the SwiftUI framework and Swift programming.

Publication date:
April 2020
Publisher
Packt
Pages
316
ISBN
9781839215421

 

Getting Started with SwiftUI

Here, we'll begin our journey into learning SwiftUI by building our very own SwiftUI app. We'll start by learning the history of the Swift programming language, which will act as a good foundation for understanding the core concepts of Swift development. Together, we'll build an app with custom animations and everyday elements that work seamlessly for iOS, iPadOS, and watchOS. From this, we'll see the benefits of writing good, clean code—once—for multiple devices. Once we have our working app, we'll cover testing and debugging, and see how crafting our code in the right way from the start can make this much simpler to implement.

We'll get started with the history of Swift before getting hands-on into Xcode, where we'll learn just how simple, yet powerful, developing in SwiftUI really is. In this chapter, we'll get you primed and ready for your journey into SwiftUI by first of all introducing you to the Swift programming language, along with the existing UIKit framework. We'll then discuss what SwiftUI brings to the table, and how it sits not only within a new project but in your existing projects too.

The following topics will be covered in this chapter:

  • Introducing Swift as a programming language
  • Learning about existing UI frameworks
  • Introducing SwiftUI
  • When to use SwiftUI, and why
 

Technical requirements

No technical requirements are needed for this chapter. We'll simply be going through an overview of Swift and SwiftUI; however, feel free to grab a coffee if you like!

 

Introducing Swift as a programming language

Whether you're a seasoned Mac/iOS developer or brand new to the scene, one way or another you'll have heard of Swift. The Swift programming language was first announced by Apple at the Apple Worldwide Developers Conference (WWDC) in 2014 and was intended to bring to the table numerous features from a multitude of other programming languages. Although not labeled as a successor, some feel that Swift was brought in to replace Apple's currently used programming language, Objective-C.

Apple had actually been developing Swift since 2010, a project originally started by Chris Lattner, who joined Apple in 2005 to work on the Low-Level Virtual Machine (LLVM) toolchain project.

Since its announcement in 2014, Swift has taken on many iterations, with the current release at the time of writing being version 5.1.

However, the first major milestone for Swift came just after the announcement of version 2 at WWDC 2015, when Apple announced that version 2.2 was being open-sourced in December of that year. This decision was met with great enthusiasm by the community, with the ability to build, modify, and contribute to the Swift programming language. This kick-started many projects, including server-side Swift.

Open source software—Software that is created and distributed by developers under specific licenses, such as Apache 2.0 GNU General Public License (GPL) and Massachusetts Institute of Technology (MIT). The different flavors of licenses determine how developers can use and distribute the software. 

As mentioned previously, Swift was created with the idea of taking the best bits of other programming languages and rolling them into one. 

Swift is known for providing benefits, such as being a type-safe language and its functional programming properties. For current macOS/iOS developers, one of the benefits of Swift is its ability to bridge and be used in conjunction with Objective-C, the benefit being that both languages use the LLVM compiler. The following screenshot shows an example of the type interface in Swift. As you can see, from line 4, there is no declaration of the type String; it is simply inferred by the value given:

Another big win for Swift is that it allows developers to write safe code. If written correctly and by implementing the correct safeguards made available in Swift, a developer shouldn't have to worry about their application ever throwing errors. Safeguarding in Swift lets you validate against objects that could be nil, with a very simple and easy-to-read syntax, which can be seen in the following example:

If you take a look at line 18 in the preceding screenshot, you'll see that we check variableString to see if it's not nil—if so, then it's assigned to the newString constant and is now safely available for use within the if statement.

In this section, we learned about the history of the Swift programming language and some of its core features. Next, we'll learn about existing user interface (UI) frameworks made available to us in Swift.

 

Learning about existing UI frameworks

With all great programming languages come great frameworks—in particular, UI frameworks. In the case of Apple, UIKit has been the UI framework of choice since Objective-C, offering everything from labels, fonts, and buttons, to animation.

Written in Objective-C, UIKit has been the binding of the iPhone UI for all developers since the beginning. With a multitude of public APIs and documentation available to developers and solid support from the community, there has been little else to offer in terms of alternatives for Apple development.

Without UIKit, everyday interactions such as tap, pinch, and zoom gestures for drawing wouldn’t be available. UIKit is even responsible for accessibility, which we'll touch on later on in this book.

The binding between UIKit and Swift can be performed in two ways: programmatically or through the Interface Builder. 

Creating the UI programmatically

Creating the UI programmatically involves writing around five lines of code, such as in the following example:

As seen in the preceding screenshot, you first need to create an instance of the UIButton, set the frame (origin and size), set the background color, give the button's label some text, set a tap gesture (what happens when you tap the button), and then add the gesture to the button.

All this is done before we even place the button within our view hierarchy, not to mention writing the code to determine what happens when we tap the button.

All in all, quite a few lines of code—for something that could end up being a simple operation.

Creating a UI via Interface Builder

The second way is via Xcode's Interface Builder. Interface Builder is a built-in graphical user interface (GUI) that allows you to use either XML Interface Builder (XIB) files, NeXTSTEP Interface Builder (NIB) files, or Storyboards to design and create your layout with ease. With Interface Builder, you can simply drag and drop components such as Views (UIView), labels (UILabel), and Image Views (UIImageView) straight onto a canvas that can be wired straight into your code. The following is an example of how a button is created in Interface Builder and shows the code to handle the button's tap event:

Interface Builder was not always part of Xcode's integrated development environment (IDE). It was originally an independent application that ran in parallel with Xcode.

Although highly regarded by the Apple community, with the introduction of Swift UIKit slowly started to show its age. Swift's clean and compact syntax started to look bloated and untidy when asked to perform simple tasks, such as creating a frame for a button or performing an animation.

Many thought that this was simply how it was going to be from now on, with a focus on bringing UIKit to macOS deemed to be a greater necessity. But little did we know that Apple was about to change the way we build apps, for the foreseeable future.

In June 2019, at WWDC, Apple introduced us to SwiftUI.

 

Introducing SwiftUI

The Apple headline for WWDC 2019 was We are going to blow your mind and, indeed, they weren't wrong. As expected, many rumors floated around WWDC, with heavy conversations around Project Marzipan (which came to be announced as Catalyst), but no-one could have foreseen the announcement of a new UI framework—specifically, one built around Swift.

What is SwiftUI? 

SwiftUI is a brand-new developer toolkit written in Swift for Swift. It presents a declarative syntax, allowing for more fluid and natural development along with more human-readable code.

It comes built into Xcode 11 and can be selected as an alternative to Storyboards when creating a new project. To include SwiftUI in your project, simply select this from the User Interface dropdown, as seen in the following screenshot:

Compared to UIKit, SwiftUI allows you to move away from imperative programming (programmatically creating UILabel and UIButton, or dragging and dropping objects around Interface Builder) and gives you powerful interfaces that can be supported across iOS, iPadOS, macOS, watchOS, and even tvOS.

This approach to app development is a true cross-Apple platform and, along with the introduction of Catalyst, in just a few clicks your iPadOS app now becomes a true native macOS app—an option that simply wasn't available with UIKit.

Syntax in SwiftUI

SwiftUI makes full use of declarative syntax, which we'll go into further in much more detail in the next chapter, but the burning question on everyone's mind was What's so special about declarative syntax? Well, quite a lot, actually. Declarative syntax brings a whole new paradigm to writing and structuring UI-based code: no more dragging and dropping elements into NIBs and Storyboards, or complex constructors and properties to set, but more of an instruction (to the compiler)-based approach to generating and displaying UI elements.

First of all, forget about previous architecture patterns used in mobile apps (or any other object-oriented) development, such as Model-View-Controller (MVC), Model-View-ViewModel (MVVM), Model-View-Presenter (MVP), and so on. Delegate patterns commonly used in iOS/macOS development are no longer needed, as declarative syntax now makes use of States.

States and updating the UI

We'll touch on States in a later chapter but, as a general overview, if you assign @State to a property, SwiftUI will monitor this property and, if it is mutated or changed, will invalidate the current layout and reload. 

Think of it in terms of a collection of data in a list. The data changes and the list is automatically updated and refreshed—no need to invoke a refresh call (or a reloadData(), as you might have previously seen in CollectionViews and TableViews).

Tools and features

Another powerful feature of SwiftUI is hot reloading—or the preview window, as it's called in Xcode. This allows you to make changes to your UI code in real time, without the need to build and rerun the app.

By creating a Preview struct inside your SwiftUI class, you can build and inject mock data, mock navigation, and images straight into your Xcode preview window. So, for example, a SwiftUI project might have a list that is dynamically populated by external data. This would allow you to inject dummy data into the preview window without running your app and calling an API.

Building for multiple devices

Whether you're building for iOS, macOS, iPadOS, tvOS, or watchOS, SwiftUI has you covered. All the features of SwiftUI can be built once and can support multiple devices, thus eliminating the need to write code multiple times.

In this book, we'll start by building an iOS app, which can be easily turned into an iPadOS app, followed by a watchOS app.

With UIKit, we had many options to build a cross-device UI right within Interface Builder, but this could often lead to complicated AutoLayout constraints, traits, or even size classes (which no-one ever really understood...).

SwiftUI's standard library is written in Swift. However, its core foundation is actually written in C++ .

Next, we'll talk about the circumstances in which we may want to use or benefit from SwiftUI.

 

When to use SwiftUI, and why

When it comes to using SwiftUI, first off, you need to start by thinking of what type of app you're building. If you're looking to build the next shoot-em-up multiplayer game, then I'm afraid SwiftUI is not for you. However, anything else—from a banking app to a catalog app—can benefit immediately from Swift UI.

The afore mentioned declarative syntax allows for States to be used in order to allow effective but— more importantly—efficient reloads of data. For those familiar with UIKit's UICollectionViews or UITableViews, you'll know that writing logic to reload the whole table in order to change just one tiny value can be both tiresome and tedious.

Designers taking their first step into development will certainly benefit from SwiftUI, with top graphical design packages already rumored to be incorporating plugins that will allow SwiftUI syntax to be exported directly from the drawing board.

The term full-stack is often used (and overused) in the development industry, particularly with web developers. A frontend web developer would generally look after the design elements and visual construction of a site, such as HTML, Cascading Style Sheets (CSS), and presentation logic, with backend web developers concentrating more on core application logic, networking, and data layers.

This type of separation is not commonly seen in mobile app development, even though developers may follow the same, or similar, architecture patterns. Could SwiftUI be the first step toward acknowledging, and even achieving, full stack mobile app development?

As we'll find out in the next chapter, SwiftUI is perfect for beginners, either young or old. Interface and application logic can be written and designed in such a way it simply rolls off your tongue as you type, almost like painting by numbers.... but for developers.

 

Summary

In this chapter, we learned the history of Swift as a programming language, and how its first big milestone kick-started a now-thriving community. We then covered how UIKit was used alongside Swift to design and develop iOS apps and touched on its aging and complex syntax. The introduction of SwifUI came as a perfect companion to Swift, opening up avenues not just for seasoned developers but also for designers and people just starting their journey into the world of Apple app development. 

Next, we are going to delve more deeply into the declarative syntax and talk about the benefits of this particular programming paradigm.

 

Questions

  1. Which paradigms do SwiftUI & UIKit follow?
  2. What was Swift's first big change?
  3. What is open source software?
  4. For which platforms can SwiftUI be developed?
  5. Which UI GUI tools were used before SwiftUI?
 

About the Author

  • Chris Barker

    Chris Barker is a senior iOS developer and tech lead for fashion retailer N Brown (JD Williams, SimplyBe, Jacamo), where he heads the iOS team, building apps for their major brands. Having now worked in the IT industry for over 22 years, Chris started his career developing .NET applications for online retailer (now BT Shop). In 2014, he made his move into mobile app development with digital agency Openshadow based in MediaCityUK. Here, he worked on mobile apps for clients such as Louis Vuitton and L'Oréal Paris. Chris often attends and speaks at his local iOS developer meetup NSManchester. Most recently, Chris attended Malaga Mobile in Spain, where he spoke about his passion for accessibility in mobile apps. Over the past 2 years, Chris has been a regular speaker at CodeMobile Developer Conference and plans to return in the future.

    Browse publications by this author

Latest Reviews

(1 reviews total)
The Book, Learn SwiftUI, does just that. Giving me the coding experience I want which I have applied to my projects all ready.

Recommended For You

SwiftUI Essentials - iOS Edition

Learn the ropes of application development for iOS 13

By Neil Smyth