Uploaded image for project: 'Swift'
  1. Swift
  2. SR-12648

RangeReplaceableCollection's 'filter' uses an intermediate array

    XMLWordPrintable

    Details

      Description

      RangeReplaceableCollection has an overload of filter that produces Self:

      extension RangeReplaceableCollection {
        /// Returns a new collection of the same type containing, in order, the
        /// elements of the original collection that satisfy the given predicate.
        ///
        /// In this example, `filter(_:)` is used to include only names shorter than
        /// five characters.
        ///
        ///     let cast = ["Vivien", "Marlon", "Kim", "Karl"]
        ///     let shortNames = cast.filter { $0.count < 5 }
        ///     print(shortNames)
        ///     // Prints "["Kim", "Karl"]"
        ///
        /// - Parameter isIncluded: A closure that takes an element of the
        ///   sequence as its argument and returns a Boolean value indicating
        ///   whether the element should be included in the returned collection.
        /// - Returns: A collection of the elements that `isIncluded` allowed.
        ///
        /// - Complexity: O(*n*), where *n* is the length of the collection.
        @inlinable
        @available(swift, introduced: 4.0)
        public __consuming func filter(
          _ isIncluded: (Element) throws -> Bool
        ) rethrows -> Self {
          return try Self(self.lazy.filter(isIncluded))
        }
      }
      

      As written, this is intended to be constructing the new collection by lazily evaluating the predicate…but lazy filters don't support throwing closures, so this is actually just using the eager filter on Sequence that produces an Array. It should be replaced with a simple loop that appends elements one-by-one to a new Self value.

        Attachments

          Activity

            People

            Assignee:
            valeriyvan Valeriy Van
            Reporter:
            jrose Jordan Rose
            Votes:
            0 Vote for this issue
            Watchers:
            6 Start watching this issue

              Dates

              Created:
              Updated:
              Resolved: