[swift-evolution] [Pitch] Improve `init(repeating:count)`

Dave Abrahams dabrahams at apple.com
Sat Sep 9 12:27:06 CDT 2017


 
on Fri Aug 18 2017, Erica Sadun 
<swift-evolution at swift.org> wrote: 
 
>> On Aug 17, 2017, at 9:29 PM, Taylor Swift 
>> <kelvin13ma at gmail.com> 
> wrote: 
>> On Thu, Aug 17, 2017 at 9:06 PM, Erica Sadun via 
>> swift-evolution 
>> <swift-evolution at swift.org 
>> <mailto:swift-evolution at swift.org>> 
>> wrote: 
> 
>>  
>>> On Aug 17, 2017, at 6:56 PM, Xiaodi Wu 
>>> <xiaodi.wu at gmail.com 
>>> <mailto:xiaodi.wu at gmail.com>> 
>>> wrote:  On Thu, Aug 17, 2017 at 7:51 PM, Erica Sadun 
>>> <erica at ericasadun.com 
>>> <mailto:erica at ericasadun.com>> wrote: 
>>> What people are doing is taking a real set of values (1, 2, 3, 
>>> 4, 5, for example), then discarding them via `_ in`, which is 
>>> different from `Void -> T` or `f(x) = 0 * x`. The domain could 
>>> just as easily be (Foo(), "b", 💩, UIColor.red, { x: Int in 
>>> x^x }). There are too many semantic shifts away from "I would 
>>> like to collect the execution of this closure n times" for it 
>>> to sit comfortably.   What arguments might help to alleviate 
>>> this discomfort? Clearly, functions exist that can map this 
>>> delightfully heterogeneous domain to some sort of range that 
>>> the user wants. Would you feel better if we wrote instead the 
>>> following?   ``` repeatElement((), count: 5).map { UIView() } 
>>> ``` 
>>  My favorite solution is the array initializer. Something along 
>> the lines of `Array<T>(count n: Int, generator: () -> T)`. I'm 
>> not sure it _quite_ reaches standard library but I think it is 
>> a solid way to say "produce a collection with a generator run n 
>> times". It's a common task. I was asking around about this, and 
>> found that a lot of us who work with both macOS and iOS and 
>> want to stress test interfaces do this very often. Other use 
>> cases include "give me n random numbers", "give me n records 
>> from this database", etc. along similar lines.   The difference 
>> between this and the current `Array(repeating:count:)` 
>> initializer is switching the arguments and using a trailing 
>> closure (or an autoclosure) rather than a set value. That API 
>> was designed without the possibility that you might want to 
>> repeat a generator, so there's a bit of linguistic turbulence. 
>> -- E   To me at least, this is a very i-Centric complaint, 
>> since I can barely remember the last time I needed something 
>> like this for anything that didn’t involve UIKit. What you’re 
>> asking for is API sugar for generating reference types with 
>> less typing. 
> 
> No, that's what the original thread poster wanted. 
> 
> I want to avoid breaking math. 

I know it's late to chime in here, but IMO (mutable) reference 
types and the exposure of === “break math,” and I think that's the 
real effect you're seeing here.

-- 
-Dave



More information about the swift-evolution mailing list