I recently discovered the utility of the snippet feature in Xcode. Currently I’m mainly developing my apps with Swift and doing the UI programatically. That’s a lot of boilerplate code and I am bored to always type the same short bit of code for each of my views.
What’s a snippet
For a detailed description of a snippet you can check NSHipster post that explain well and is still relevant.
TL;DR: A snippet is a small bit of re-usable code or text.
Xcode already provide some snippets for common patterns in swift and objective-c. You can find them by clicking on the + button located on the Xcode top bar.
Why do I need snippets
As explained at the beginning of this article, I does all my UI related stuff programmatically and UI is composed of a lot of boilerplate code, especially for the view declaration.
This is how I initialize a label :
The goal is to strip the initialisation code of all our app specific values, then you will have the perfect candidate for a snippet. Now that we know the idea, we can create our first snippet by simply selecting a part of your code, right click and select create code snippet.
The snippets is now created and contains the code you selected.
A this point the snippet is ok but we can improve it. We will add some placeholders for the values that can change between each label you will setup. adding a placeholder is easy, they are delimited by <# and #> tokens.
Update the code in the snippet with the declaration below.
We also want to add a completion shortcut, we will go with “customLabel”.
Now if you type customLabel in a swift file, the autocompletion will suggest your snippet, tap enter and voila all your label UI code is added, you just have to replace the placeholders with the desired values.
You can find below some of my UI snippets that I use often.
Thanks for reading ! 😊