If you are ever trying to get the compile time of a particular function down then hopefully the following examples will be of some use. For me, the best option from the following examples is to split long functions into smaller, composite functions.
To easily see the compile times of functions I created an empty project and added an Other Swift Flags (this can be found inside $Your Project -> Build Settings -> Swift Compiler - Custom Flags) of -Xfronted -warn-long-function-bodies=1. Doing this means Xcode will warn you everytime that you build if any function in your project took longer than 1 millisecond to type check.
Please note that these examples are just that - examples. Your mileage may vary and I would recommend not to take these as must-dos. In most cases, it makes more sense to write code that is clear and understandable - not code that compiles quickly but is confusing to yourself and others.
As you might expect, if you explicitly tell the compiler what type the values are, then you have significantly faster compile times. Option C was the only function body that did not prompt a warning for compile time being >= 1ms. Option D only took 1ms though so the difference is negligible.
I had often suspected ?? to be slower to type check than a guard or if let function but in this short example there appears to be no significant difference.
Interestingly, simply naming your arguments significantly reduces compile-time - even if you don’t explicitly type the named arguments.
A nice feature of Swift is its ability to add custom subscripts. The most common one I’ve seen used is the safe operator to safely access array values.
The subscript option is clearly the cleanest implementation, but annoyingly it also takes the longest to compile by a good amount.
Splitting Up Long functions
For this example, I’ve taken some sample UITableViewCell code and have two options. One option has all the setup in one function. The other option has three functions, one function does half the setup, another the other half and the main function calls the other two. The time I’ve recorded is the total time for both options.
This example is perhaps the most useful of all the examples on this page. It is much better for compile time if you split your functions into smaller composite functions. The best thing about this is that generally this also results in more readable code.