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

Erica Sadun erica at ericasadun.com
Thu Aug 17 21:20:55 CDT 2017


> On Aug 17, 2017, at 7:38 PM, Xiaodi Wu <xiaodi.wu at gmail.com> wrote:
> 
> On Thu, Aug 17, 2017 at 8:25 PM, Erica Sadun <erica at ericasadun.com <mailto:erica at ericasadun.com>> wrote:
> `repeatElement((), count: 5)` is better than `1 ... 5`, but `Count(3).map({ UIView() })` is far more elegant.  I'd still probably go with an array initializer or `5.elements(of: UIView())`. I don't think I'm overstating how common this pattern is, and `Array(repeating:count:)` feels _close_ but not close enough.
> 
> The first two have the benefit of being currently existing APIs;

I'm pretty sure Count isn't an  existing API. And as I said before, while I don't think this rises to stdlib inclusion, it's been a common problem domain for people both inside and outside Apple so it deserves a full discussion.

That said, `Count` is neat. It encapsulates an idea in a way that I haven't seen in Swift. 

-- E


> they capture the semantics perfectly, as I've argued, and I simply don't see how they are impaired in elegance in any way--certainly not enough to justify a standard library addition to create a third way of spelling the same thing. Ultimately, any user is free to define something like:
> 
> ```
> func * <T>(lhs: Int, rhs: @autoclosure () throws -> T) rethrows -> [T] {
>   return try repeatElement((), count: lhs).map { try rhs() }
> }
> 
> 5 * UIView()
> ```
> 

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


More information about the swift-evolution mailing list