> On Oct 12, 2016, at 3:21 AM, Jean-Denis Muys via swift-users 
> <swift-users@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: 
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:


It also makes a lot more possible: 

let people = ["David", "Chris", "Joe", "Jordan", "Tony"]
let winner = people.random()
swift-users mailing list

Reply via email to