UIResponder Extension -- To get any type of responder if exists in hierarchy

extension UIResponder {

func chainedResponderOf<T: Any>(type responderClassType: T) -> UIResponder? {

    guard let classType = responderClassType as? AnyClass else { return nil }
    
    var responder: UIResponder? = self.next

    while responder != nil {
        
        if responder!.isKind(of: classType) {
            return responder!
        }
        responder = responder!.next
    }
    
    return nil
}

}

1 Like

Hi Fahid,

I expect this is a suggestion for an extension on UIKit for the Swift Interface? If so, unfortunately UIKit is out of scope for our modification. That said, it may be a good suggestion for Feedback Assistant that Apple could include for UIKit, and could also be useful for others using Swift anyway in their own codebase!

Rod

1 Like

As a matter of interest, this might be a cleaner implementation?

extension UIResponder {

    func chainedResponder<T: UIResponder>(of responderType: T.Type) -> T? {

        return sequence(first: self, next: { $0.next })
                       .dropFirst()    // Drop the first one as it will be self
                       .first(where: { $0 is T }) as? T
    }
}
2 Likes

Thanks @Rod_Brown

What is the way to suggest Apple to add this in UIKit?

Apple has recently switched to using native apps for bug reports and feature requests. You can find out more here: