Acceptance In Principal/Proposed Further Discussion
Thanks to everyone for participating in this review. The core team intends broadly to accept the proposal, but would like further discussion in a few specific areas of the API design.
Below are the areas we would appreciate further discussion on. In particular, the question of static methods versus free functions, and the value vs reference type nature of generators.
Any posts on the specific topics below would be much appreciated. The review period will be extended to Monday, April 16th to allow for this discussion.
Generators as reference vs value types
The nature of the generator API implies that the generators must be reference-y, since they aren’t passed
inout to functions like
shuffle, but aren’t required to be reference types. This isn’t great. The options are:
- live with this
- require they be a
- change the APIs so they are taken
Requiring classes forces an allocation for cases where the generator does not need to hold mutable state (for example, in a generator that sources from the OS). However, that allocation probably is not material to the other costs involved in random number-related operations.
inout makes the API more weighty to use. It would imply that generators could be value types. Value-typed seeded generators could easily lead to bugs – the user may not realize that by making a copy, they are essentially forking the generation at the point of the copy.
inout would be the correct syntax for a move-only generator type, once Swift has this concept, which would prevent this problem.
Static versus free functions
The team thinks making the
random(in: Range<T>) family free functions, rather than static methods on
T, may help with discoverability. There is also a term-of-art argument to be made: many APIs have
random as a free function. If going with the term-of-art justification, this would also suggest that the argument label could be dropped too.
The team felt that
Collection.randomElement would work better than
.max, the word “random” doesn’t noun well, so adding “Element” improves readability. The team agrees that this method should return an optional value rather than trap, consistent with similar APIs like
The core team believes it would be better to leave implementation details of the default source to the individual platforms, rather than defining the implementation for each platform as part of the proposal. The characteristics of the implementation should be documented by each platform. Implementations are strongly encouraged to prefer a secure RNG if this is practical on their platform. The team agrees with the decision to not have the generator API be failable.