Adding custom code snippets to Xcode

Posted by on May 8, 2017

I am sure you have been there. This is the you can’t remember which time you look in your old code to be sure how to do something you are sure you have done thousands of times but still for some reason you can’t recall it completely so you just copy paste it and then change what you need. If only you could have that in some part in Xcode where with just one click you can use it and continue coding without looking in old projects.

This is where Code Snippets come to action. A great, mostly unknown, tool on Xcode.

In my case, background threading in Swift is one of those snippets I always look for on old projects or somewhere on the internet. That’s why I created a code snippet for it and now I don’t have to do anything else than just start typing “backgroundThreading” and click enter.

You can access the code snippets library in the right bar on Xcode.

Then at the bottom just select the second option.

I will show you the easiest way to add your own snippets here.

First of all you will need to type your code as the way you want to use it in the future. In my case is this:

This is the easiest way to perform a background process and then call the main thread after everything is done.

Once you have your code you need to select it and then just drag it to the code snippets section.

After this a pop up will appear asking you for more information about your new snippet.

  • Title Stands for the main identifier of your snippet
  • Summary A brief description of what it does for future references
  • Platform The default is All, but you can choose between iOS, macOS, tvOS and WatchOS, and according to your project configuration it will be shown or not
  • Language You can choose from a variety of languages, the default is Swift or Objective-C depending on the file you have open
  • Completion Shortcut This is the keyword that you are going to use while coding of autocomplete
  • Completion Scopes Tells Xcode when it should suggest the snippet on your code

After that you just click Done and the new snippet would be available for clicking on the library with the badge User so you know is a custom snippet.

But the easiest way to use it is just start typing the shortcut and then Xcode will suggest it, just click enter and you are done.

And that’s all, you’re ready to go and add as many snippets as you want to make your coding faster and less prompt to errors.

Comments

Be the first to comment.

Leave a reply

Simple Business by Nimbus Themes
Powered by WordPress