Search code examples
swiftswift3xcode8

Overloads for '...' exist with these result types: ClosedRange<Bound>, CountableClosedRange<Bound>


Swift 2

let gap = CGFloat(randomInRange(StackGapMinWidth...maxGap))

Missing argument label 'range:' in call

Swift 3 - new error

let gap = CGFloat(randomInRange(range: StackGapMinWidth...maxGap))

No '...' candidates produce the expected contextual result type 'Range'

Overloads for '...' exist with these result types: ClosedRange, CountableClosedRange


Solution

  • As of Swift 3, ..< and ... produce different kinds of ranges:

    • ..< produces a Range (or CountableRange, depending on the underlying type) which describes a half-open range that does not include the upper bound.
    • ... produces a ClosedRange (or CountableClosedRange) which describes a closed range that includes the upper bound.

    If the randomInRange() calculates a random number in the given range, including the upper bound, then it should be defined as

    func randomInRange(range: ClosedRange<Int>) -> Int {
        // ...
    }
    

    and you can call it as

    let lo = 1
    let hi = 10
    let r = randomInRange(range: lo ... hi)