FREE: Watch my new YouTube videos, Xcode in 20 Seconds! >>

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

Sponsored You’re already busy updating your app for Swift 4.2 and iOS 12, so why not let Instabug help you find and fix bugs? Add just two lines of code to your project and receive comprehensive reports with all the feedback you need to ship a world-class app – click here to learn more!

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.

Download for free!

Want a free 75-minute video teaching functional programming, protocol-oriented programming, and more? This is your lucky day!

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 >>