Category: iOS

Creating Document-Based Apps with SwiftUI

Xcode 12 Note from the Author

Xcode 12 made a bunch of changes to SwiftUI for document-based apps. If you choose a multi-platform document app project, you will get the text editor project I create in this article without having to write any code. I’m keeping this article up for people who are still using Xcode 11.

The article Make a Markdown Editor in SwiftUI shows how to create a document-based SwiftUI app with Xcode 12.

Start of Original Article

I have not seen any articles or tutorials on creating a document-based app with SwiftUI so I’m writing one. In this tutorial you will build an iOS plain text editor.

If you haven’t already, I recommend reading two articles before going through the tutorial. Creating Document-Based iOS Apps Part 1 provides an overview of creating document-based iOS apps. Using Text Views in a SwiftUI App provides an explanation of using a UIKit text view in a SwiftUI app. SwiftUI does not currently have a built-in text view.

Create the Project

Start by creating a project. Create an iOS document-based app project. Choose SwiftUI from the User Interface menu if it’s not already selected.

The most interesting files Xcode creates for a document-based SwiftUI app are the following:

  • DocumentBrowserViewController.swift contains code for the document browser, where people create and open documents.
  • DocumentView.Swift contains code for the document’s main view.
  • Document.Swift contains code for the document.

Creating a New Document

If you run the project, you’ll notice that tapping the Create Document button does nothing. You must write some code to create the document when someone taps the button. The easiest way to create a new document is to add an empty file to the project. The empty file should have the same file extension as the document’s. This file will be copied to the app bundle when building the project. You’ll have to write some code to load the file from the app bundle.

One last thing to do to create documents properly is to configure the document type in Xcode so that the app is an editor of plain text files.

Add an Empty Document File

Choose File > New > File to add a new file to the project. Select Empty from the list of iOS file templates. The empty file is in the Other section. You have to scroll down a bit to reach the Other section.

Name the file. I named the file New Document.txt. You can choose a different name, but remember the name.

Load the Empty Document

Open the DocumentBrowserViewController.swift file and go to the didRequestDocumentCreationWithHandler function. Replace the following line of code:

With the following code:

This code loads the empty document file from the app bundle and uses that as the base for a new document.

There is one more piece of code to change. In the same function, find the following code:

There is a problem with the code inside the if block.

This line of code moves the file from the application bundle. Your app will crash the second time you create a document because the empty document file was moved out of the application bundle. The fix is to copy the file from the application bundle when creating a new document.

Edit the Document Type

Xcode initially sets the document type for an iOS document-based app to be a viewer of image files. You must configure the document type in Xcode so that the app is an editor of plain text files. You’re making a text editor, not a text viewer.

Select the project from the project navigator to open the project editor. Select the app target from the left side of the project editor. Click the Info button at the top of the project editor to access the document types. Click the disclosure triangle next to Document Types.


  1. Enter PlainText in the Name text field.
  2. Enter public.plain-text in the Types text field. public.plain-text is the UTI (Uniform Type Identifier) for plain text files.
  3. In the Additional document type properties section, set the CFBundleTypeRole value to Editor so people can edit documents.
  4. Set the LSHandlerRank value to Alternate to ensure this text editor isn’t the default text editor for all plain text files.

Create the Data Model

The data model for this project is simple. The document is the data model. All you have to do is add a property to store the text. Open the Document.swift file and add the following code inside the Document class:

The code declares a property to store the text and has the initial value of an empty string.

Building the Text View

Now it’s time to add the text view so people can edit text. Currently SwiftUI does not include a text view so you have to write code to create a UIKit text view. But it’s not too much code. Add a new Swift file to your project for the text view. Import the SwiftUI and UIKit frameworks. Add the following struct:

The text view must conform to the UIViewRepresentable protocol, which is the protocol that allows the use of UIKit views in SwiftUI apps. To conform to the protocol, you must write the following functions:

  • makeUIView
  • updateUIView
  • makeCoordinator

The makeUIView function creates and configures the view. The function takes an argument of type Context and returns the type of view you want to make, which is UITextView for a text view. The Context type is a type alias for the context where updates to the UIKit view take place.

The code listing creates a text view, configures the view so people can edit large amounts of text, and adds some padding so the text isn’t on the left edge of the screen. The code also sets the view’s delegate to the context’s coordinator, which you will create shortly.

The updateUIView function handles updates to the view.

I will fill in this function later.

The makeCoordinator function creates a coordinator so the UIKit view can communicate with data in SwiftUI.

Create the Coordinator

Add a Coordinator class inside the struct for the text view.

The class inherits from NSObject, which is the base class for all UIKit classes. A text view’s coordinator should conform to the UITextViewDelegate protocol so it can respond to text view notifications, such as the text changing.

The coordinator needs a property to hold the UIKit view and an initializer. I will be adding more to the coordinator later in the article.

Add the Text View to the Document View

The last step to adding the text view is to have the document view display it. Open the DocumentView.Swift file. Inside the body property you should see a VStack that contains a HStack and a button. The HStack shows the name of the file. The button lets you go back to the browser when you’re done writing.

The text view should appear between the HStack and button. Add the following line of code between the HStack and button:

If you build and run the project, you should be able to create a new document and type in it.

Connect the Text View to the Document

For the app to do more than let people type text in a text view, you must connect the text view to the document so the text you type updates the document as well. In the document view, you should see the following variable:

This variable contains a reference to the document. Make the following changes to the variable:

The @State property wrapper will allow the text view to bind to the document in order to display the document’s text. Changing the type of the variable to Document is also necessary for the text view to work with the document properly.

Now add the following property to the text view:

The @Binding property wrapper binds the document property in the text view to the document property in the document view. The text view and document view are both pointing to the same document. The text view now has access to the document.

Now that you created the binding you must go back to the document view and change the call to create the text view by supplying the document as an argument.

The $ at the start of $document indicates that you are passing a binding to the text view. You must pass a binding so the document view and text view both point to the same document.

Fill the updateUIView Function

Now that the text view has access to the document, you can write the text view’s updateUIView function. Set the text view’s contents to the document’s contents.

Handling Text Changes

One last thing to do is to update the document when the text view contents change. Add the following function to the Coordinator class:

The first line of code sets the document’s contents to the text view’s contents. The second line marks the document as changed so it will be saved.

Save the Document

At this point you’re finished with the SwiftUI material, but there’s still some work to do to finish the app. The text editor is missing one really big feature: saving text. Open the Document.Swift file. Xcode created a blank contents function for saving the document.

What you have to do is convert the text in the document to a Data object and archive that object. Apple provides the NSKeyedArchiver class and an archivedData function so you can do both steps in one line of code.

The root object is the document’s text. Requiring secure coding ensures your app will be able to unarchive the data when loading the document.

Load the Document

After saving the document, the next task is to load the document when someone chooses a document from the browser. Xcode supplies a blank load function, where you write the code to load the document from disk.

The first argument to the load function is the contents of the file. You must first cast the contents to the Data type. Call the NSKeyedUnarchiver class’s unarchiveTopLevelObjectWithData function to unarchive the text from the file. The last step is to set the document’s text to the contents of the file.


Now you have a simple, working text editor. You can create documents, edit text, save documents, and open them. You can use this project as a foundation for building your own text editing app, such as a Markdown editor. I have the project on GitHub for you to download if you run into issues.

Using Text Views in a SwiftUI App

SwiftUI currently lacks native support for text views. (Note: Xcode 12 adds text view support to SwiftUI). If you want people to enter large amounts of text in a SwiftUI app, you have to wrap a UIKit or AppKit text view. This article shows you how to use a text view in an iOS app that uses SwiftUI. Most of this material should also apply to Mac apps. Replace anything that has a UI prefix with NS.


To use UITextView in a SwiftUI app, you must create a struct for the text view and have it conform to the UIViewRepresentable protocol. The UIViewRepresentable protocol is how you wrap UIKit views in SwiftUI apps.

Don’t forget to import the UIKit framework.

Create the View

To conform to the UIViewRepresentable protocol, you must add two functions to the struct you created. The first function is makeUIView, which creates and configures the view. It takes an argument of type Context and returns the type of view you want to create, which is UITextView for a text view. The Context type is a type alias for the context where updates to the UIKit view take place. The following code shows an example of creating and configuring a text view:

At a minimum you must create the view and return it. In the code sample I decided to make the text view scrollable and editable. I also added some padding so the text isn’t on the left edge of the screen.

Update the View

The second function you must write is updateUIView, which handles updates to the view. The updateUIView function takes two arguments: a view and a context.

I will be filling the function later in the article.

Try Creating Your Own Text View

At this point you have enough to add a text view to a SwiftUI app. Create an iOS app project in Xcode. Add a file for the TextView struct. Fill the struct with the code I’ve shown so far in the article. Open the ContentView.swift file and replace the text label in the body property with a text view.

Build and run the app. You should be able to type in the text view.

Connecting to Your Data Model

At this point you can type in the text view, but you’ll lose what you type when you quit the app. For a text view to be useful, it needs a connection to your app’s data model.

In the struct for the text view, add a property for the data model. For a simple app, you can create a @State property wrapper that holds the text.

In a real app you’re more likely to have a reference to the data model in another SwiftUI view. Use the @Binding property wrapper to access data from another SwiftUI view.

Replace MyModel with whatever the name of your data model is.

Now that you have a connection to your data model, you can fill in the updateUIView function. Make the text view show the text from the data model.


In order for a UIKit view to communicate with data in SwiftUI, the view needs a coordinator. To conform to the UIViewRepresentable protocol, you must add a new function to the TextView struct, makeCoordinator. The makeCoordinator function creates the coordinator. The return type takes the form StructName.Coordinator.

The next step is to set the text view’s delegate to the context’s coordinator. Add the following line of code to makeUIView before the return statement:

The last step is to add a class for the coordinator. Create a class for the coordinator inside the struct for the text view. Make sure the name of the class matches the name you supply to the makeCoordinator function.

The Coordinator class inherits from NSObject, which is the base class for all UIKit and AppKit classes. A coordinator for a text view should conform to UITextViewDelegate so it can respond to text view notifications, such as the contents of the text view changing.

The coordinator needs a property for the control it’s going to coordinate. The control property contains a reference to the text view.

The Coordinator class needs an initializer to set its view, which is the control property in the code sample.

The last block of code tells the coordinator to respond when the contents of the text view change. The function sets the model’s contents to the text view’s contents. If you want the text view to handle other notifications, add the functions to the coordinator.

Responding to Text Changes in Mac Apps

Responding to text changes has more differences in Mac apps. Let’s look at the code to respond to text changes on Mac.

The name of the function is textDidChange. Instead of taking the text view as an argument, it takes a notification. The object property of the notification is the object that sent the notification. When entering text, the text view is the object that sends the notification that the text changed. The guard statement ensures the object that sent the notification is a text view. The property to get the text in NSTextView is string, not text.


To use UIKit views in a SwiftUI, you must perform the following tasks:

  • Create a struct for the view that conforms to the UIViewRepresentable protocol.
  • Write the makeUIView function to create and configure the view.
  • Write the updateUIView function so SwiftUI can update the view.
  • Write the makeCoordinator function to create a coordinator for your view to communicate with SwiftUI data.
  • Create a class for the coordinator.

I have a simple plain text editor project on GitHub if you want to see an example of a SwiftUI project that uses a text view.

Learn SwiftUI or UIKit?

With the release of SwiftUI in iOS 13, a common question from people new to iOS development is whether they should learn SwiftUI or UIKit.

Why Learn SwiftUI

The most compelling reason to learn SwiftUI is it’s the future. 2–3 years from now, most iOS developers will use SwiftUI to build their user interfaces. You’re eventually going to need to learn SwiftUI so you might as well learn it now. It makes sense to learn SwiftUI instead of learning UIKit and learning SwiftUI a year or two later.

SwiftUI Limitations

SwiftUI is new technology. At the time I’m writing this, SwiftUI has been out for six months, and three of those months it was in beta. Because SwiftUI is new technology, it has bugs and missing features. Apple is going to be making changes to SwiftUI over the next few years so there’s going to be a lot of work keeping up with the changes. Should you decide to learn SwiftUI instead of UIKit, prepare for a lot of frustration.

Apple’s SwiftUI documentation is limited at best. Many outsiders have been writing books, articles, and tutorials on Swift UI. But at this time, everyone is a beginner at SwiftUI development. There’s much less SwiftUI learning material than UIKit.

SwiftUI has a limited set of user interface elements. For example SwiftUI currently lacks text views and collection views.

SwiftUI apps don’t run on iOS 12 and earlier iOS versions. For people new to iOS development, this isn’t a big limitation, but it is a limitation.

Why Learn UIKit

UIKit is mature and stable. It has all the available iOS user interface elements. There is a lot more UIKit learning material available than SwiftUI.

If you want to use a text view, collection view, or another view that SwiftUI doesn’t have, you need to know some UIKit.

Should You Learn SwiftUI or UIKit?

If you can put up with the SwiftUI limitations I mentioned earlier and deal with limited documentation, learn SwiftUI. Otherwise learn UIKit.

Creating a Simple SwiftUI App

SwiftUI is Apple’s new framework for building user interfaces in Swift. Let’s introduce SwiftUI by creating a simple app. The app displays the number of times you tap a button. I couldn’t think of a simper app idea.

I’m going to focus on making an iOS app in the article, but you can also make a Mac version of this app. Create a macOS App project instead of an iOS project.

Apple added SwiftUI support in Xcode 11 so you must be running Xcode 11 or higher to use SwiftUI.

Create the Project

Create a single-view iOS app (App on Xcode 12) project. Choose SwiftUI from the User Interface menu. Deselect all the checkboxes.

When you create the project, the project navigator should look similar to the following screenshot:


The file you’re going to edit in this article is ContentView.swift. This file contains the main view for the app’s user interface. You will be adding controls to the content view.

The Content View

Open the ContentView.swift file. You’ll see the following struct for the content view:

The body property contains the main view. In the code Apple supplies, the view consists of a label (the Text struct is a label) with the text Hello, World!. If you build and run the project, you will see the label.

Previews and the Canvas

If you look at the end of the ContentView.swift file, you’ll see the following struct:

That struct is for displaying a preview of the view in Xcode’s canvas. The canvas is next to the Swift file in Xcode so you can view your source code and the canvas side by side..

I’m not going to use previews and the canvas in this article. I find the canvas gets in the way, is flaky, and doesn’t help much. But the canvas is there for you if you want it. You can toggle the canvas on and off using a button on the right side of the jump bar.


The button is at the top left in the screenshot.

Change the Label

Let’s start by changing the label’s text to Taps:. Change the code for body to the following:

Build and run the project, and you should see the label’s text is Taps:.

You can modify how the text in the label looks using functions and properties of the Text struct. Start with a period. The following code displays the label in bold text:

The following code changes the font to the system title font:

Add a Variable to Store the Tap Count

To display the number of times someone taps the button, you need a variable to store the number of taps. Add the following code before the body variable:

You must use the @State property wrapper so you can change the value of taps when someone taps the button. If you omit the @State part, you will get a compiler error saying that you’re trying to change an immutable value.

Now modify the label so it also shows the number of taps.

Build and run the project. The label will show zero taps.

Place the Label in a Stack

The next logical step is to add a button. But you can’t just add the button after the label.

The compiler will complain about that code. You have to place the label and button inside a stack. Start by placing the label inside a stack.

I placed the label in a vertical stack. When you add the button, it will appear below the label. Build and run the project. There aren’t any visible changes, but you’re ready to add the button now.

Add the Button

Let’s add the button to the stack in the content view.

The button’s title, Tap Me, is in parentheses. A closure for the button’s action (what happens when someone taps the button) follows. For this app you increment the taps variable. If you have more complicated behavior, write a function and call that function from the closure.

Build and run the project. The number of taps increases each time you tap the button.

Add Space Between the Label and Button

The app works, but there’s not much space between the label and button. Use the padding function to add some padding between the label and button.

If you supply no arguments, the padding function adds a small amount of space. To add more space, you can supply the edge to apply the padding and the amount. The following line of code provides 100 points of padding at the bottom:

When you build and run the project, you should see better spacing between the label and button.


Add a Reset button that sets the taps variable back to zero. Don’t forget to add padding between the two buttons. I have the project on GitHub if you get stuck.

Going from Tutorials to Your First Real Swift App: First Steps

If you want to learn iOS development, there are many places for you to learn. Hacking with Swift has two free 100 day courses for learning iOS development, one with UIKit and one with SwiftUI.

Getting started with iOS development normally isn’t the big issue. Go through a book or course, and you’ll learn the basics of iOS programming. The trouble starts when you finish a book or course and start to make your first app on your own. You feel stuck and don’t know where to start. You share some of the following feelings:

  • “I’m a little lost as to where to go next. I’ve completed Swift for Beginners courses on at least four different sites, and if I build one more My First App I may cry.”
  • “I just am having a hard time finding the tutorials/courses I specifically need to acquire the skills I need for MY project. I’m frankly not even sure I know what skills I actually need because so much of the information I’m seeing is so outdated that I’m not sure it’s relevant to me or if I’ll begin working on it only to find it’s no longer the way things are done or that there’s a better way after I’ve put in a lot of effort.”
  • “Making the jump from basic concepts to actual coding is hard.”
  • “Basic lessons have very basic concepts but when I look at the code being used in other projects, they use methods and syntax I’ve never seen.”
  • “I watched almost every video (Stanford course) and I did everything that professor do. I built them all. But when I’m trying to build apps alone, even the things I built earlier I can’t do anything. I know Swift syntax and other stuff but I just can’t program.”

Why Do You Feel Stuck?

When you were following the book, course, or tutorial, you were doing the equivalent of watching someone make an app. You weren’t making the app. When you try to make your own app, you get stuck because you don’t have the book, course, or tutorial telling you what to do.

To apply to what you learned, you have to make an app on your own. And there’s a lot less material on going from beginner to making your first real app than there is on getting started.

Step 1: Choose a Suitable Project

The first step you have to take when creating an app is choosing the app to make. When choosing an app to make, you must balance the following:

  • Making something small enough that you can finish.
  • Making something that interests you.

A big mistake many new iOS developers make is starting with a huge app. They want to make something like Uber or a social media app with realtime chat, something that requires people to sign up for an account to use the app. Making a social media app requires you to have a backend server with a database to store all the data. No iOS development tutorial or book is going to teach you things like that. No wonder people feel stuck.

For your first app make something small and relatively simple. Make an app that uses only Apple technologies. Make something that you have a chance to finish. Once you finish your first app, choose something more ambitious as your next project.

But you also have to make an app that interests you. If you choose an app that bores you, you’ll stop making it.

Step 2: Learn the Necessary Frameworks to Make Your App

You may be able to skip this step if you pick a simple enough app to make. But most projects force you to learn some additional frameworks to make the app.

If you open Xcode’s documentation window (choose Help > Developer Documentation in Xcode), you’ll see that Apple has dozens of frameworks for iOS developers. There’s no way for you to learn them all. Use your choice of project to determine the frameworks you need to learn.

  • A fitness app may use HealthKit.
  • An app that uses locations may use MapKit.
  • A text editing app uses TextKit. You may even need to learn about UIDocument and making document-based apps.
  • A drawing app may use PencilKit and Quartz2D.
  • An app that generates PDF files uses PDFKit and possibly Quartz2D.

Step 3: Do a Little Planning

You may be tempted to create a new project in Xcode and start writing code. But development will go more smoothly if you do some planning before you start writing code. You don’t have to plan everything upfront, but doing the following will help you:

  • Draw the screens for the app on paper
  • Make a list of the app’s must-have features
  • Make a list of the types of data your app uses

Once you do some planning, pick the simplest feature you can implement and work on that. When you get a small part working, you’ll feel good and use that energy to move on to the next part of the app. Build the app piece by piece, and you’ll eventually finish your first app.

Are You Doing It Right?

You may be wondering as you develop your app if you’re doing things the right way. I can’t tell you if you are, but it’s software, not something physical. Code can be changed and improved. If you find out you’re doing things wrong, you can change the code so you’re doing thing the right way.

I recommend placing your project under version control. Using version control makes your code easier to change. If you make a bunch of mistakes, you can go back to a working version of your code. When you create a project in Xcode, there’s a checkbox to place your project under version control. You can place an existing Xcode project under version control by choosing Source Control > Create Git Repositories.

Timers in Swift

A timer sends a message to an object after a certain amount of time passes. Start by declaring a variable for the timer.

Starting a Timer

Call the scheduledTimer method to start a timer. The scheduledTimer method takes the following arguments:

  • A time interval for how often the timer fires, specified in seconds.
  • Target, which is the object that receives the message from the timer.
  • Selector, which is the function the target should run after receiving the message.
  • UserInfo, which is optional additional information you can send.
  • Repeats, which indicates whether the timer runs once or repeats.

The following code starts a timer to autosave data every 30 seconds:

The function for the selector needs @objc at the start of the declaration.

Stopping a Timer

Call the invalidate method to stop a timer. The following code stops a timer:

Limiting an iOS App to Friends and Family

I sometimes see questions on forums from people who have developed an iOS app and want only friends and family to be able to install the app. Apple does not currently allow you to restrict an app to friends and family, but there are two alternatives that will allow you to effectively reach that goal.


Apple now has unlisted app distribution for releasing apps that won’t appear in App Store listings.

Put the App on the App Store

The simplest solution is to just put your app on the App Store. Many of you think this is a bad idea, that putting your app on the App Store will allow anyone with an iOS device to install the app.

Technically you’re correct. When you put an app on the iOS App Store, anyone can install the app. But no one will know your app exists. The only people who will install your app are the people you tell about the app.

In early 2017 I released a free word game for iOS and Mac, LetterMiner. When I released the game I got a few dozen downloads on the iOS App Store due to the game being new. But then the downloads dried up. In almost three years, I have had fewer than 100 downloads of the iOS version. And I wanted people to play the game.

As long as you don’t publicize the app, your app will effectively be limited to your inner circle of friends and family. You may get a few outside downloads when you first release the app, but after that the downloads will trickle down to zero. There are so many apps on the App Store that people are not going to stumble upon your app by browsing the store.

Keep the App Perpetually in Beta

A more complicated solution is to keep your app perpetually in beta and add your family and friends as beta testers in TestFlight.

The advantage of TestFlight is that no outsiders will be able to install your app. The disadvantage is that you have to submit a new beta build every 90 days. That’s why I recommend putting your app on the App Store. Release your app once and as long as you avoid publicizing the app, you will reach your goal of limiting your iOS app to friends and family.

I have a great idea for an app. How do I get started?

I see this question come up a lot. Someone has an idea for an iOS app, and they want to know how to get started making the app. You have two options for making an iOS app: hiring a developer to make the app or making the app yourself.

Hire a Developer to Write the App for You

Hiring a developer is expensive. A good iOS developer charges $100(US) or more per hour. If you can afford to hire a developer, you can find one at iOS Dev Directory.

You may think you can hire someone to write an iOS app for a percentage of the profits. Unless you have a friend who’s an iOS developer, you’re going to have a tough time finding someone to work for a percentage of the profits. Working for a percentage of the profits is basically working for free because the chances of making lots of money from an iOS app are slim. Most people are unwilling to work for free.

Learn Programming

The cheaper, more time consuming option is to make the app yourself. If you’re asking how to make an iOS app, chances are high you have never programmed before. Learning to program is the first step in making an iOS app. Trying to develop an iOS app without knowing how to program is like trying to write a book without knowing how to write. It’s going to be very difficult.

Swift is the language to learn to develop iOS apps. Get a book to learn Swift. People recommend the following books to learn Swift:

Despite Apple’s claims, Swift is not an easy language to learn. If you struggle learning Swift, I recommend learning Python and going back to learn Swift. Python is an easier language to learn than Swift. Once you learn Python or another programming language, learning Swift will be easier.

Learn iOS Development

Once you learn how to program, you can move on to learning iOS development. My Learning iOS Development article has many resources for learning how to make iOS apps.

Fixing and Avoiding Crashes in Swift Code

When you start out developing iOS or Mac apps in Swift, you run into a common problem. Your project builds without any errors but crashes when you run it. It’s frustrating to have your code not work, and the cryptic messages Xcode spews don’t help much.

In this article you’ll learn how to get Xcode to show you where the crash occurs in your code. You’ll also learn the most common causes of crashes in Swift apps and how to avoid them.

Add an Exception Breakpoint to Locate the Crash

Adding an exception breakpoint in Xcode makes it easy to find where your code crashes. Open Xcode’s breakpoint navigator by choosing View > Navigators > Show Breakpoint Navigator.


Click the Add (+) button at the bottom of the breakpoint navigator and choose Exception Breakpoint. A popover opens for the breakpoint.


Make sure the Exception menu is set to break on all exceptions and to break when an exception is thrown.

Now when your app crashes, Xcode breaks into the debugger and shows you the line of code where the crash occurred. Showing the line of code where the crash occurred comes in handy when you’re trying to figure why your app crashed.

If you look at the screenshot of the breakpoint navigator, you will notice the exception breakpoint is in the User section. User breakpoints apply to all projects so you don’t have to set them for each project.

Because exception breakpoints help so much to find where your apps crash, they’re strong candidates to be user breakpoints. To make a breakpoint a user breakpoint, select it in the breakpoint navigator, control-click, and choose Move Breakpoint To > User. Now the exception breakpoint will fire when any of your projects crash.

Common Crash Causes

Now that you can determine where your app crashes, you want to know why your code is crashing and how to fix it. Without seeing your code, I can’t tell you exactly why your code is crashing, but I can tell you the most common causes of crashes.

  • Unwrapping a nil Swift optional
  • Disconnected outlets
  • Accessing an element outside an array’s bounds
  • Accessing an uninitialized variable

Unwrapping a Nil Optional

The leading cause of crashes in Swift apps is unwrapping a nil optional value. When you unwrap a nil optional value, you will see the following error message in Xcode’s debug console:

This error is usually caused by two things. First, force unwrapping an optional by adding an exclamation point to a variable’s name. Second, using as! to downcast an optional value to a specific type.

The fix is to avoid force unwrapping. Use if let or guard statements to safely unwrap your optionals. Use as? instead of as! when downcasting. The following articles provide more detailed information on optionals:

Disconnected Outlets

The second most common cause of crashes in Swift apps is having a disconnected outlet for a user interface element and accessing that outlet in your code.

You can check if an outlet is connected in Xcode’s source code editor. Next to an outlet is a circle. The following screenshot shows a disconnected outlet:


A connected outlet has the circle filled in.


To connect the outlet open Xcode’s assistant editor so the storyboard and the source code file are both open. Select the user interface element in the storyboard. Hold down the Control key and drag to the outlet in the source code file.

Out of Range Array Access

If you try to access an element in an array that is not in the array’s range, your app will crash. Out of range errors are usually off-by–1 errors because array indices start at 0 instead of 1. An array with 10 elements has indices 0–9, not 1–10. If you try to access the tenth element with the following code:

The app will crash with an out of range error because the subscript [10] references the 11th member of an array with only 10 elements.

You can also get an out of range error if you try to access elements in an empty array. An empty array has no elements so any subscript is out of range. Swift arrays have an isEmpty property you can check to see if the array is empty.

Accessing an Uninitialized Variable

This error usually occurs in view controllers when you try to access a property in viewDidLoad or similar initialization function. viewDidLoad is called before the code that initializes the property, causing a crash.

A common fix for accessing a property before it’s initialized is to access the property in viewDidAppear, which gets called after viewDidLoad.