Swift用泛型找到给定类的超级视图

Chr*_*ski 10 generics recursion parent superview swift

我想我正在与仿制药斗争.我想创建简单的UIView扩展,以递归方式查找函数param中传递的类的超级视图.我希望函数返回可选的包含nil的对象,或者作为提供的类的实例可见的对象.

extension UIView {
    func superviewOfClass<T>(ofClass: T.Type) -> T? {
        var currentView: UIView? = self

        while currentView != nil {
            if currentView is T {
                break
            } else {
                currentView = currentView?.superview
            }
        }

        return currentView as? T
    }
}
Run Code Online (Sandbox Code Playgroud)

任何帮助非常感谢.

efr*_*dze 14

斯威夫特3

这是一种更简洁的方式:

extension UIView {

    func superview<T>(of type: T.Type) -> T? {
        return superview as? T ?? superview.compactMap { $0.superview(of: type) }
    }

    func subview<T>(of type: T.Type) -> T? {
        return subviews.compactMap { $0 as? T ?? $0.subview(of: type) }.first
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 你不需要 `flatMap`,因为在 `flatMap` 中调用 `superview()` 会导致递归。让我们简单地写下 `return superview as? ?? superview?.superview(of: type)`。希望编译器优化这个尾递归。 (5认同)