Several blog posts have highlighted sluggish compile times associated with Swift code. I encountered this issue during a test case involving the creation of a relatively straightforward nested structure, leading me to suspect that type inference was the root cause.

In Xcode 6.1, the following code snippet takes an astonishing 40 seconds to compile:

swiftfunc hangCompiler() { ["A": [ ["B": [ 1, 2, 3, 4, 5 ]], ["C": [ ]], ["D": [ ["A": [ 1 ]] ]] ]] }
If your code includes numerous nested declarations, it seems that the type inference solver could be responsible for significant delays. To identify the slow parts of your compile time, I navigated to the “Report Navigator” tab in Xcode during the slow build, selected the ongoing build, and clicked the horizontal bar button next to “Compile Perf.swift” to reveal the Xcode command being executed. Although the line is lengthy, it resembles something like this:
bash /Applications/ -frontend -c -primary-file .../Perf.swift ...x86_64/Perf.o
I then copied and pasted this command into a new window. While it was processing, I pressed CTRL-\ (control+backslash), and it provided valuable information:
  • While type-checking ‘doPerf’ at /tmp/SwiftPerformance/Perf.swift:12:5While type-checking expression at [/tmp/SwiftPerformance/Perf.swift:12:5 – line:12:76] RangeText=”[“A”: [ [“B”: [ 1, 2, 3, 4, 5 ]], [“C”: [ ]], [“D”: [ [“A”: [ 1 ]] ]] ]]”
  • To enhance compile time, you can offer hints to the type inference engine by introducing some explicit casts:
    swift["A": [ ["B": [ 1, 2, 3, 4, 5 ]] as [String: [Int]], ["C": [ ]] as [String: [Int]], ["D": [ ["A": [ 1 ]] as [String: [Int]] ]] ]]
    These subtle hints reduce the compile time to 0.18 seconds.If you encounter slow compile times with specific source files, you can pinpoint the problematic lines by pasting in the compiler command and pressing CTRL-. If nested type inference is the culprit, you can expedite the process by incorporating casts strategically.

    Leave a Reply

    Your email address will not be published. Required fields are marked *