Skip to content

An Intro to SwiftUI

Posted on:March 20, 2023

Table of contents

Open Table of contents

SwiftUI: An Introduction

SwiftUI is Apple’s modern, preferred way of building an application for their platform. There’s a lot to like about SwiftUI:

While today, SwiftUI is a phenomenal choice for building an application, we have to acknowledge one of it’s primary downsides: SwiftUI can get often get a product or view to 95% of where it needs to be with minimal effort — but the last 5% can often remain elusive. Despite that, it’s important to remember that SwiftUI can integrate very well with UIKit applications. We can use SwiftUI in an existing UIKit application quite easily, and we can mix in some UIKit into our SwiftUI code.

Knowledge of both frameworks allows us to perform the task of seamlessly mixing and matching each framework to maximize the effects of what each excels with.

What’s In A View

The basic building block of SwiftUI is the View. Views are a deceptively simple concept within SwiftUI. In order to declare a new view, we need a simple struct that conforms to View and fulfills the requirement of having a body property, like so:

import SwiftUI

struct MyView: View {
  var body: some View {
    EmptyView()
  }
}

While the code above is short & compiles, there are several things to note about it:

  1. We use a struct, not a class. There are performance considerations due to the relative weight of a UIView, developer considerations due to the mechanics of a pass-by-value vs pass-by-reference object (with the latter, we have to be much more careful of retain cycles and memory leaks). structs are also limited by their design: they aren’t freely mutable in the same way that a class is; functions that mutate values must be marked as such. The net effect is that a struct as the base object for a view ensures that a view is a simple collection of values that transforms those values into a UI, with limited knowledge and responsibility to interact with the outside world.
  2. The View protocol is quite simple. It has three components, two of which are required. For the purpose of this section, we’ll only talk about the body requirement, of type some View. This requirement means that we must return some concrete type which conforms to View within body.

The View is your basic building block within SwiftUI. The list of built-in views is [quite long], but within that list may be items that are quite surprising — within this list are Color and various gradient types. Returning Color.blue is just as valid as returning a complex multi-layered user interface.

In the next section, we’ll look into creating our own view with its own mutable state.


Footnotes

  1. The live preview can be extended to UIKit as well, via SwiftUI’s PreviewProvider class. Later in this book, we’ll explore how to seamlessly get previews from any UIKit view.

  2. We can build to macOS via Catalyst, but it’s complex and well outside of the scope of this book.