More on supporting repeating initializers with closures

(Saw the original thread while researching something else.)

Continuing the discussion from Support repeating initializers with closures not just values:

Maybe a better parameter name could help:

extension RangeReplaceableCollection {

    /// Creates a collection with the given number of elements, each created by
    /// separate calls to the given closure.
    ///
    /// - Precondition: `count >= 0`.
    ///
    /// - Parameter count: The number of elements to create.
    /// - Parameter body: The closure to call each time to return an initial
    ///   element.
    /// - Postcondition: The collection has `count` elements, resulting from
    ///   `count` calls to `body`.
    ///
    /// - Complexity: O(*n*), where *n* is the length of the collection.
    public init(distinctCallCount count: Int, of body: () throws -> Element) rethrows {
        self.init()
        reserveCapacity(count)
        for _ in 0..<count {
            append(try body())
        }
    }

}

I don't think this needs to be a customization point.

1 Like
Terms of Service

Privacy Policy

Cookie Policy