Automate Repeated Code Blocks in Swift

Meet XCTemplate

Tolga Taner
3 min readApr 16, 2022
Photo by Kenny Eliason on Unsplash

Sometimes almost every task is often similar to another one from some aspects. There is always a boilerplate code for those tasks and there are common part of each other. For example, if we want to list something, we always prefer UITableView or we want to list and configure something we prefer UICollectionView for UIKit. When we create a new file in iOS, there is a empty file and we fill the emptyness. This is the default template in iOS. You may be bored about common code blocks such as writing configure(), delegate, datasource protocol setting etc. Instead of doing this over and over again, there is a new approach named customXCTemplate to create custom file that contains some repeated code to much saving time, increase development speed whatever you called.

The default templates location is

/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/Xcode/Templates/File Templates/iOS/Source

If we navigate to this location by pressing Command+Shift+G in Finder, we can easily see that templates folder is corresponding to iOS tab in Xcode.

Let’s say that we use MVVM design pattern in the project so for every new implementation of module, we have to create files of MVVM pattern model, view model, view, respectively. Instead of creating 2 common files every time, we can write a custom xctemplate to create them from the one base.

To achieve that, we need to navigate this location

~/Library/Developer/Xcode/Templates/

After navigating, we need to create a new folder named custom. Inside of custom folder, we should create a new folder too named MVVM.xctemplate

Final structure is like this

In MVVM.xctemplate, Let’s create one Swift file named ___FILEBASENAME___ViewModel for a view model and one Swift file for view controller named ___FILEBASENAME___ViewController and one TemplateInfo.plist file for its configuration.

Open TemplateInfo.plist for configuration, we have to set HiddenFromLibrary set to 0, HiddenFromChooser set to 0, otherwise we can not see the template in Xcode creating file window.

Now, let’s configure ViewController and ViewModel file to open it, respectively.

Let’s return to Xcode and create a new file from Custom tab, MVVM type. It generates two file these are ViewController file and ViewModel file.

As we can see, we create our xctemplate file to increase development speed for MVVM pattern. Thanks for reading.

--

--