Helpful iOS and Xcode Code Snippets
Organize your code and create new snippets to use in your codebase
Writing clean and readable code is always important, but organizing it well is too.
The best way to separate your code within a file in iOS development is using MARKs, and instead of writing these MARKs every time, you can just use a code snippet like this one:
This code snippet shows a way to separate your
UIViewController into sections. Depending on your architecture, it may vary which MARKs are necessary. This snippet is for a simple MVC architecture.
Another useful code snippet may be used in the models:
Note that the dash (
// MARK: -) adds a nice separation line between MARKs in the jump bar. On Xcode 11, you can see the same separation in the Minimap view.
Benefits of MARKs Code Snippets
- Consistency across files.
- Consistency across projects.
- Shared MARKs for developers.
- Organization of the code.
- Developer performance.
Create Your Own Code Snippet
Any code can be a code snippet, not only MARKs. Actually, each of the benefits applies for every code snippet.
If you want to create a new code snippet in Xcode, you just need to select a portion of code, right-click on it and choose the option Create code snippet. Then, you can edit and delete it by pressing
How to use them
There are two ways:
Lto see a list of all your code snippets, then select one.
- (Recommended) Assign a completion when creating the code snippet and then just type it in the code and the option to add it will pop up. Tip: add a keyword at the beginning of all your code snippets, then just type that word and access all of them.
Share It With Your Team
~/Library/Developer/Xcode/UserData/CodeSnippets and send all your
.codesnippet files, or add them to a GitHub repo.
After adding the files to the folder (if the folder doesn’t exist, create it), restart Xcode, and start using the snippets for all your projects.
Available Code Snippets
Before creating your own code snippets collection, check out mine in this GitHub repo. You are welcome to contribute.