Rolling your own snippets
So, now it gets much more interesting. You can (and most definitely should) create your own snippets of any code that you use frequently and which involves more than a trivial amount of typing. You can then also assign a keyboard shortcut to your user snippet, which is a lot faster than calling up the Utilities pane and searching and scrolling your way through the whole list.
It's kind of ironic that Xcode's method to create user snippets is to select the code you want to store as a snippet, and then drag the text into the snippets list. Are we not coders? Can we not do this with our keyboards? It would seem the people in Cupertino think not:
- So, go ahead: drag some code into the snippets list, and you'll see a new snippet appear. It will be where you dragged it to, although it will be alphabetically sorted along with the rest as soon as you close and reopen the Utilities pane.
- Double-click on the new snippet to open up a pane in which you can see the snippet's contents, as in the following screenshot:
- So now, as you can see in the preceding screenshot, we have an Edit button. Clicking that will take you to the snippet-editing window:
Here you can tailor the snippet in a number of ways:
- The Title is what appears in the snippets list in the Utilities window.
- The Summary is, well, a summary, if you need one.
- You can restrict a shortcut to a particular Platform or programming Language, which enables you to use one shortcut for different versions of the code snippet, the most obvious ones being Swift and Objective C.
- The Completion Shortcut is text only, no modifiers. When you type the shortcut into your code, it will be included in the code-completion list (assuming you have not deactivated it).
- You can also restrict the snippet to one or more particular scopes:
Again, this allows you to use one shortcut for several snippets, according to the context, as well as restricting the degree to which code completion is cluttered by shortcuts you will not use in a given context.
If you wish to restrict a snippet's scope, but have it available to more than one scope, use the + button beside the Completion Scope menu.
/Users/.../Library/Developer/Xcode/UserData/CodeSnippets
You might even like to store them on GitHub for those spontaneous coding sessions away from home.
It really is worth getting into the habit of creating your own code snippets--there is no limit to the number you can have (at least, I'm not aware of anyone discovering one) and they offer the biggest bang for your buck in terms of increased coding speed.