[swift-evolution] [Proposal] Random Unification

Jeremy Pereira jeremy.j.pereira at googlemail.com
Wed Oct 11 11:07:52 CDT 2017


I’m a bit late to the party on this one, but has anybody considered the fact that you need a way for the user of the interface to override the default random number source?

For example, some applications require a cryptographically secure source, others might eschew perfect entropy for speed. Still others might want repeatability e.g. Minecraft lets you enter a seed when it does the World generation so you can go back and play the same World again and again. For unit testing, you might want to replace the random number generator with a sequence of hard coded values so you can exactly control the code path that the test takes.

So if you have a protocol that describes an API for generating random numbers called RNG, the extension on Int would look something like

extension Int {
  init(randomInRange: Countable{Closed}Range<Int>, rng: RNG = /* a CS random number generator */)
}

> On 7 Oct 2017, at 04:24, Chris Lattner via swift-evolution <swift-evolution at swift.org> wrote:
> 
> 
>> On Oct 5, 2017, at 10:58 AM, Nate Cook via swift-evolution <swift-evolution at swift.org> wrote:
>> 
>> The edge case is really the same (empty ranges), it’s about what we do with the edge case. If we include the methods on integer types, usage will look like this:
>> 
>>     let x = Int.random(in: 0..<5)     // 3
>>     let y = Int.random(in: 0..<0)     // runtime error
>> 
>> If we only have the collection methods, usage will look like this:
>> 
>>     let x = (0..<5).random()!         // 3
>>     let y = (0..<0).random()!         // runtime error
> 
> These aren’t the forms I was suggesting, what I meant was:
> 
> extension Int {
>   init(randomInRange: Countable{Closed}Range<Int>)
> }
> 
> which gives:
> 	let x = Int(randomInRange: 0..<5)
> 
> The point of this is that you’re producing an Int (or whatever type).  Regardless of whether the initializer is failable or not, this is the preferred way of creating a new value with some property: it is an initializer with a label.
> 
> -Chris
> 
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution



More information about the swift-evolution mailing list