FREE: Follow my new 100 Days of Swift challenge! >>

How to fix the error “Expression was too complex to be solved in reasonable time”

Paul Hudson       @twostraws

Swift’s use of type inference makes our code shorter and easier to read, but it also chews up a lot of CPU time. Sometimes a value could be one of several types, and if it gets used with another things that could be one of several types then the amount of work Swift has to do multiplies. If Swift encounters something with so many possibilities that it simply can’t figure it out after about 15 seconds, it throws an error instead: “Expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions.”

This is something the Swift team are working to improve with every new version of Swift, and there’s no real fixed cut-off for when the compiler will throw this error. However, at the time of writing Swift 4.2 is the latest available version and you can cause the error with code as simple as this:

let a = 0
let sum = abs(a + a) + abs(a + a) + abs(a + a)

The combination of operator overloading and function overloading means that code is simple but certainly isn’t easy – at least not for Swift.

Fortunately, this error message tells you exactly what you need to do to fix the problem: break up the expression into multiple subexpressions. That is, calculate independent parts individually, then combine them together. The trivial example from above would become this:

let a = 0
let part1 = abs(a + a)
let part2 = abs(a + a)
let part3 = abs(a + a)
let sum = part1 + part2 + part3

Available from iOS 8.0

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Average rating: 4.0/5

Click here to visit the Hacking with Swift store >>