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
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!
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.
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.
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.
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 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.
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:
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.
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.
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.
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.
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).
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.
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...).
Next, we'll talk about the circumstances in which we may want to use or benefit from SwiftUI.
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.
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.
- Which paradigms do SwiftUI & UIKit follow?
- What was Swift's first big change?
- What is open source software?
- For which platforms can SwiftUI be developed?
- Which UI GUI tools were used before SwiftUI?
- SwiftUI: https://developer.apple.com/xcode/swiftui
- WWDC: https://developer.apple.com/wwdc19/
- Declarative Programming: https://en.wikipedia.org/wiki/Declarative_programming
- Open Source Software: https://en.wikipedia.org/wiki/Open-source_software