Swift find superview of given class with generics

眉间皱痕 提交于 2019-12-22 04:07:20

问题


I guess I'm struggling with generics. I want to create simple UIView extension to find recursively a superview of class passed in the function param. I want the function to return optional containing obviously either nil, or object visible as instance of provided class.

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
    }
}

Any help much appreciated.


回答1:


Swift 3/4

This is a more concise way:

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
    }

}

Usage:

let tableView = someView.superview(of: UITableView.self)
let tableView = someView.subview(of: UITableView.self)



回答2:


No need to pass in the type of the class you want (at least in Swift 4.1)…

extension UIView {    
    func firstSubview<T: UIView>() -> T? {
        return subviews.compactMap { $0 as? T ?? $0.firstSubview() as? T }.first
    }
}


来源:https://stackoverflow.com/questions/37705819/swift-find-superview-of-given-class-with-generics

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!