Search code examples
iosswiftcocoa-touchuiviewuikit

How can I make a Sequence to iterate over all the ancestors (superviews) from a UIView up the view hierarchy to the root?


I'd like for UIView to have a property that returns a sequence of all the ancestors of the view up the hierarchy. That would be useful for purposes like finding the nearest one that matches a particular type:

let tableView = cell.ancestors.first(where: { $0 is UITableView })

What's a nice way of implementing that ancestors property?


Solution

  • Using the sequence(first:next:) function, from the Swift Standard Library, an even shorter solution is possible as well:

    extension UIView {
        var ancestors: AnySequence<UIView> {
            return AnySequence<UIView>(
                sequence(first: self, next: { $0.superview }).dropFirst())
        }
    }