[swift-evolution] [Proposal] Random Unification

Nate Cook natecook at apple.com
Thu Oct 5 12:02:53 CDT 2017

> On Oct 5, 2017, at 11:30 AM, Ben Cohen via swift-evolution <swift-evolution at swift.org> wrote:
>> On Oct 4, 2017, at 9:12 PM, Chris Lattner via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>>> ```
>>> extension Int {
>>>   static func random(in range: Countable{Closed}Range<Int>) -> Int
>>> }
>> Nice.  Should these be initializers like:
>> extension Int {
>>   init(randomIn: Countable{Closed}Range<Int>)
>> }
> I don’t see much of a case for making it it random(in: SpecificCollection) instead of genericCollection.random().

I see a couple points in favor of these static methods (or initializers) on the numeric types:

1) The collection method will need to return an optional to match the semantics of existing methods (like min()). If this is the only method available, every time someone needs a random value in the range 1...10, they’ll need to unwrap the result (with either force unwrapping, which people will complain about, or some kind of conditional binding, which is its own problem). Even if the semantics are the same (trapping on an empty range), the user experience of using a non-optional method will be better.

2) Floating-point ranges won’t get the collection method, so either we’ll have inconsistent APIs (random FP value is non-optional, random integer is optional) or we’ll make the FP API optional just to match. Both of those seem bad.

> One possible reason is if you exclude half-open ranges, only having CountableClosedRange, then you don’t have to account for the possibility of an empty collection (via an optional or a trap) because they cannot be empty. But closed ranges aren’t the currency type – half-open ranges are. So it’d hit usability if you have to convert from one to t'other often.
> Other possibility is discovery. But given the common use case is “random element from collection”, I don’t expect this to be an issue as it will quickly become common knowledge that this feature is available.

Agreed here—I don’t think discovery is really an issue between the two kinds. However, I don’t think the overlap in features (two ways to generate random integers) are a problem, especially as we’d have better alignment between integer and floating-point methods.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20171005/74443531/attachment.html>

More information about the swift-evolution mailing list