> On 17 Aug 2017, at 10:38, Adrian Zubarev via swift-evolution 
> <swift-evolution@swift.org> wrote:
> This is a small pitch which I will abandon if there is not much appetite for 
> such improvement. ;)
> I would like to propose an improvement to an initializer of all collection 
> types that provide: init(repeating repeatedValue: Element, count: Int).
> This change is meant to support reference type initialization on each 
> iteration of the internal for-loop rather than copying the same references n 
> times.
> The change would be really straightforward and should not break existing 
> code, except that the behavior would change for class types.
> Instead of:
> init(repeating repeatedValue: Element, count: Int)
> let threeViews = Array(repeating: UIView(), count: 3) // contains 1 view 3 
> times
> we would have:
> init(repeating repeatedValue: @autoclosure () -> Element, count: Int)
> This simple change would allow us to construct an array of different objects 
> instead of an array with n references to the same object.
> let threeViews = Array(repeating: UIView(), count: 3) // contains 3 different 
> view
I don't think that changing the existing initialiser is the way to do this, as 
it's not really clear here that the UIView() will be instantiated multiple 
times rather than the same reference copied multiple times. The copying 
behaviour is in fact desirable as it will be significantly faster, especially 
with very large arrays.

I think the better way to achieve this might be add some closure-based sequence 
that returns a closure's result N times, so we could do something like this:

        let threeViews = Array(Repeat(count: 3) { return UIView() })

i.e- we would initialise Array from a sequence returning a new UIView three 
times. While we could also do an array initialiser with closure, using a 
separate type is probably the cleaner way to do this.

There is already a Repeater type, but this just does the same as the array 
initialiser already does, could be another type I've missed that might do what 
is needed, otherwise it seems to require types like AnyIterator with some 
counting code.
swift-evolution mailing list

Reply via email to