Did you know that you can create your own file templates for Xcode? Sure you did. But did you also know that you can create a template that takes a string and puts it into a field you define?
Let’s build a file template for a Swift protocol and a protocol extension.
Create a file template
First things first.
Xcode looks for your custom templates at the location
~/Library/Developer/Xcode/Templates/. We will start by copying a template that comes with Xcode to that location.
Open Terminal.app and create a directory for your custom templates like this:
Next copy the template for Swift file to the new folder:
When you now create a new file in Xcode, you find the new template in its own section:
But this is only the normal Swift file template. We want something better. Open
___FILEBASENAME___.swift in Xcode by putting the following into Terminal.app:
Replace its contents with this:
Now, open an Xcode project and create a file using your new template. Call it Foo.swift and click Create.
Xcode creates the following file:
Nice! But we can do more. Let’s say we want to have a template that creates a protocol and an extension with one method. To be able to do that, we need options.
Open TemplateInfo.plist and add an Options array. Fill in the values that the plist looks like this:
If you prefere your plists in source code form the complete plist looks like this:
With this you have added two text fields to the file creation process. The first is for the name of the file/protocol. The second will be used to generate a method in the protocol and the extension. Don’t forget to save the plist file.
When Xcode creates the file, it uses the values in the text fields and puts them into placeholders in the file template. To see how this works, open
___FILEBASENAME___.swift again and replace its content with this:
Don’t forget to save the file.
Now, open again an Xcode project, add a new file and select your template. An options window opens:
Put in Foo for the protocol name and bar for the method and create the file. The generated code looks like this:
Nice! You have just created a template that can create a protocol with an extension and a method. I’m sure, you will find lot’s of other useful templates to create. Also have a look at the templates provided by Apple to find out what’s possible.
I’d love to read your feedback about this. You can find me on Twitter.