[swift-evolution] [Proposal] Random Unification

Martin Waitz tali at admingilde.org
Thu Nov 30 17:46:13 CST 2017


Hello Jonathan,

> For collections, I think we should call returning a random element -randomElement, and choosing a random element without replacement -popRandomElement

I disagree because I don’t think that the random data is a property of the collection.
The collection is not the subject which has random elements, it’s more the object which is used when drawing an element.

> var list = [1,2,3,4]
> let a:Int? = list.randomElement //List is still [1,2,3,4] and ‘a’ contains one of the elements

Instead I would prefer to have something like:

let a = random.draw(from: list)

> let b:Int? = list.popRandomElement //Now list contains all the elements except the one in ‚b’

we already have remove(at:), this can be used trivially:

let b = list.remove(at: random.draw(from: list.indices))

a little bit more verbose, but easily understandable.
It uses well known building blocks and does not increase the API surface of collections.

— Martin



More information about the swift-evolution mailing list