[swift-users] How to be DRY on ranges and closed ranges?
David Hart
david at hartbit.com
Wed Oct 12 08:17:29 CDT 2016
I’ve been bitten by that quite a few times. I’m not a fan of the new distinction between Range and ClosedRange. I understand the reasoning behind them, but the new model is creating more problems for me than the it solves.
David.
> On 12 Oct 2016, at 12:21, Jean-Denis Muys via swift-users <swift-users at swift.org> wrote:
>
> Hi,
>
> I defined this:
>
> func random(from r: Range<Int>) -> Int {
> let from = r.lowerBound
> let to = r.upperBound
>
> let rnd = arc4random_uniform(UInt32(to-from))
> return from + Int(rnd)
> }
>
> so that I can do:
>
> let testRandomValue = random(from: 4..<8)
>
> But this will not let me do:
>
> let otherTestRandomValue = random(from: 4...10)
>
> The error message is a bit cryptic:
>
> “No ‘…’ candidate produce the expected contextual result type ‘Range<Int>’”
>
> What is happening is that 4…10 is not a Range, but a ClosedRange.
>
> Of course I can overload my function above to add a version that takes a ClosedRange.
>
> But this is not very DRY.
>
> What would be a more idiomatic way?
>
> Thanks,
>
> Jean-Denis
>
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20161012/a7300d80/attachment.html>
More information about the swift-users
mailing list