[swift-users] How to be DRY on ranges and closed ranges?

Dave Abrahams dabrahams at apple.com
Sun Oct 16 17:31:25 CDT 2016


on Wed Oct 12 2016, Hooman Mehr <swift-users-AT-swift.org> wrote:

>> On Oct 12, 2016, at 3:21 AM, Jean-Denis Muys via swift-users <swift-users at swift.org> wrote:
>> 
>> 
>> But this is not very DRY.
>> 
>> What would be a more idiomatic way?
>> 
>
> The more idiomatic way is to look at API design in a new way. Note these points:
>
> 1. `Countable` variant is preferred when you want to deal with integer ranges as it more closely
> matches the element type.
> 2. Both countable range variants share a common protocol conformance already:
> `RandomAccessCollection`
> 3. Swift API design prefers member functions to free functions.
>
> Hence a more idiomatic (Swifty) API would probably be something like this:
>
> extension RandomAccessCollection {
>
>     func random() -> Iterator.Element? {
>
>         guard count > 0 else { return nil }
>
>         let offset = arc4random_uniform(numericCast(count))
>
>         let i = index(startIndex, offsetBy: numericCast(offset))
>
>         return self[i]
>     }
> }
>
> Using the above, both cases work and there is no repetition:
>
> (4..<10).random()
> (4...9).random()
>
>
> It also makes a lot more possible: 
>
> let people = ["David", "Chris", "Joe", "Jordan", "Tony"]
> let winner = people.random()

Hey, that is pretty awesome!

-- 
-Dave



More information about the swift-users mailing list