Increase productivity by using custom code snippets
How to create custom code snippets in xcode
While development many times we write repetitive code. Usually, we follow copy-paste but in this approach we need to remove old code and then add new code which is kind of time consuming.
I created custom code snippets when I started my career in iOS development but then I forgot for a while. Few days back, I read about custom code snippets by Alex Bush and realized it’s really a good tool to use during development.
Code snippets are also useful when you don’t generate architecture classes by script for each module.
There are so many pre defined code snippets in xcode. You just have to drag the required snippet to your editor area and use it. Sometimes you may have to edit some variable names as per requirement.
Steps for creating custom code snippet:
- Write a piece of code and select. Right click on selected code and select
Create code snippet
Note: Placeholders are placed inside <# #>
2. A window will appear and there you can rename it and add a summary.
Title: Name of code snippet, we can name it Test snippet
Summary: Description of code snippet
Platform: iOS can be selected
Language: If it’s swift specific, then select Swift
Completion shortcut: Shortcut name with which snippet can be invoked later
Completion Scopes:
- All: By default, it’s
All
, it works everywhere. Multiple scopes can be added by tapping on+
icon - Class Implementation: If we want the shortcut to work just inside a class implementation. It would work also in structs and Swift extensions.
- Code Expression: We may use this option with a snippet which is a ternary operator.
- Function or Method: If the shortcut should work just inside a function.
- String or Comment: Custom log message or comment template
- Top Level: If the shortcut should work just at the top-level i.e. outside class.
3. Once snippet is created it can be use from Snippet library by double-click or drag n drop. Actual values or variable names can be replaced with placeholder.
4. A snippet can be deleted by Left click + delete button.
5. Import/Export Custom Snippets: Custom snippets can be found at
~/Library/Developer/Xcode/UserData/CodeSnippets
Complete gist can be find here: