[swift-evolution] [Proposal] Random Unification

Martin Waitz tali at admingilde.org
Fri Dec 1 11:39:52 CST 2017


> With a protocol defining random() and random(in:), you could write generic algorithms on things which know how to create themselves from a RNG.  With your approach the RNG has to provide a way to get a random value for each type you want to support.

This is right, if we want a generic prototype for construction of random objects, well then we need such a protocol and a new method or initializer.
However, I‘m not yet convinced that such a protocol is necessary.
Most objects will be constructed using randomized values, according to the use case at hand. A generic randomizable protocol would not help here.

> For example, without random(in:) or random(), how would you get a CGFloat between 0 and 1?  Ranges are only collections if they are countable…

I was assuming that there would be a random.draw(from:) for ranges.

>> extension RandomFoo {
>>   func draw<T: Collection>(from urn: T) -> T.Element? {
>>       guard !urn.isEmpty else { return nil }
>>       let idx = draw(from: urn.indices)
>>       return urn[idx]
>>   }
>> }
> This will call itself repeatedly and hang...

You are right, Collection.indices is also a Collection. We have to explicitly use the range here.

>> We just have to define one base protocol for such extensions. Every random number generator then automatically knows how to draw elements from ranges and collections.
> It isn’t automatic, thought.  How would I get a random color?

This has already been discussed: you either want some random color from a fixed set, or you want to produce a new color using some random values. A completely random color it totally useless.

— Martin

More information about the swift-evolution mailing list