Creating a reusable file template in xcode

This article explains the steps for creating a file template in xcode . This is extremely helpful in creating constants, util classes, theme manager classes , data models etc..

Xcode looks for your custom templates at the location ~/Library/Developer/Xcode/Templates/ . We want to create a file template in xcode. Open Terminal.app and create a directory for your custom templates like this:

mkdir -p ~/Library/Developer/Xcode/Templates/File\ Templates/Custom

Next: Copy the template for Swift file that comes along with xcode to the new folder (run the following command in terminal app):

cp -R /Applications/Xcode.app/Contents/Developer/Library/Xcode/Templates/File\ Templates/Source/Swift\ File.xctemplate/ ~/Library/Developer/Xcode/Templates/File\ Templates/Custom/Utility\ Class.xctemplate 

This will copy the Swift File template to the new folder and name it as Utility Class. Now open xcode project and create a new file. Scroll down and you can see the new file template under “Custom section”.

Image for post
Image for post
Fig.1

Now go to the custom folder location and open ___FILEBASENAME___.swift. It will look like this.

// ___FILENAME___
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
//___COPYRIGHT___
//
import Foundation

This is the normal swift file format. But we may need something other than a basic swift file. We need to have a class declaration with the file name given and a set of default utility methods along with it. So open the file and replace the contents with the following.

May be you can also add a disclaimer or licence information in the file header here as you see in github open source projects.

Utility template sample code.

Save and close the file. Now create a new file using this template and name it as Utility.swift .

This is what the new file looks like.

Image for post
Image for post

Now you can add as many reusable methods as you like to this template class and reuse it with ease in every projects.

Enjoy!!

source: Swiftandpainless Article.

Written by

iOS and tvOS developer, dreamer, photographer 🤨

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store