Daily iOS
UIKit

View hierarchy traversal

How would you write a function that starts at a root view and finds a view matching some condition (say, tag == 99 or a specific type)?

func findView(in root: UIView, where predicate: (UIView) -> Bool) -> UIView?
How would an interviewer hear this answer? You'll see whether they'd move on, dig in, or say no, and which sentences would trip you up. Your score doesn't change.
See the short answer

The view hierarchy is a tree, so pushing subviews onto a queue and testing the predicate as you go finds views closer to the root first. Consume the queue with a head index instead of removeFirst to stay O(n).

Share a question