7

I'm having an error when compiling a project in Xcode, it says:

Expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions

here's the code:

static func random(min: CGFloat, max: CGFloat) -> CGFloat {
    return CGFloat(Float(arc4random()/0xFFFFFFFF) * (max - min) + min)
}
JAL
  • 41,701
  • 23
  • 172
  • 300
lagro23
  • 123
  • 1
  • 6

1 Answers1

7

Why not reduce the complexity for the compiler by breaking the expression down into two sub-expressions?

static func random(min: CGFloat, max: CGFloat) -> CGFloat {
    let rand = CGFloat(arc4random()/0xFFFFFFFF)
    return (rand * (max - min) + min)
}

You can also use UINT32_MAX (or the more "Swifty" UInt32.max or .max) in place of 0xFFFFFFFF to improve readability. If I recall, 0xFFFFFFFF is the hex value of the max value of an unsigned 32-bit Integer as defined in the <stdint.h> header.

#define UINT32_MAX 0xffffffff  /* 4294967295U */
JAL
  • 41,701
  • 23
  • 172
  • 300
  • 2
    I think this misses the point (or at least the question I wanted answered!): what does that compiler error mean??? – N_A Nov 19 '15 at 03:23
  • What do you think it means? The expression was too complex for the compiler, and it timed out trying to resolve the `+` and `*` operator overloads: https://devforums.apple.com/message/1097960#1097960 – JAL Nov 19 '15 at 03:25
  • 1
    Ah! Overload resolution. Got it. – N_A Nov 19 '15 at 03:32
  • 1
    `UInt32.max` is a bit more Swift-y: `let rand = CGFloat(arc4random() / .max)` – Stuart Nov 19 '15 at 14:11
  • @Stuart great point! Edited my answer to also include this style option. – JAL Nov 19 '15 at 14:33