Folding and Unfolding Code in Swift

By Jesse Feiler

As you browse through your Swift code in Xcode or in a playground, you can hone in on areas you’re concerned with by folding and unfolding the sections of code you’re not interested in at the moment. Folding and unfolding affects the display only: The code is still there. Folded code will be compiled.

Folding and unfolding is available for syntactic elements of code. This figure shows part of application(_:didFinishLaunchingWithOptions:) at the top of AppDelegate.swift in the example app.


Move the pointer over the code. As you pass over the function, the rest of the code is shown with a gray background so that the function itself is made more prominent. At the top and bottom of the function (lines 17 and 29), small arrows appear in the margin. Click either arrow to fold up the function. When folded up, the function will appear as shown here. Note the small arrow in the gutter at line 17:


Folding isn’t limited to functions. You can fold up almost any syntactic element: if, switch, or any of the loop constructs.

There are a number of indications that code is folded up. For example, the yellow ellipsis (a series of three dots, as in . . .) that appears in Line 17 is an indicator of folded‐up code.

Also, folded‐up code produces a discontinuity in line numbers. If you’ve chosen to show line numbers (an option you can set in the Editing section of the Text Editing tab in Xcode preferences), you can see that the line numbers in this example skip from 17 to 30 because lines 18 to 29 have been folded up.

You can unfold a section by clicking on the arrow in the margin or by double‐clicking the ellipsis.