1

I am trying to make a function that, by given a UIView, it iterates recursively to all the subviews until it finds a UIView of type T. So far I have:

func getType(from view: UIView) -> AdaptiveContainerView? {

    for aView in view.subviews {
        if let adapView = aView as? AdaptiveContainerView {
            return adapView
        }
        else {
            return getType(from: aView)
        }
    }

    return nil

}

Now I am trying to refractor the function so it gets the UIView type and returns it if found. By UIView type I mean:

class MyView: UIView {}

My first approach is

func getGenericType<T, Q:UIView>(from view: UIView, ofType: T) -> Q? {

    for aView in view.subviews {
        if aView is ofType {

        }
        ...
    }

    return nil

}

However I am having the following error:

Use of undeclared type 'ofType'

Any ideas?

Thank you

Reimond Hill
  • 4,278
  • 40
  • 52

1 Answers1

1

For Static

func getGenericType<Q:MyView>(from view: UIView) -> Q? {

    for aView in view.subviews {

        if let res = aView as? Q {

            return res
        }
        else {

            return getGenericType(from: aView)
        }

    }

    return nil
}

Call

let res = getGenericType(from: self.view) // res of type MyView 

If you need to dynamically send the parameter

func getGenericType<T:UIView>(from view: UIView,type:T.Type) -> T? {

    for aView in view.subviews {

        if let res = aView as? T {

            return res
        }
        else {

            return getGenericType(from: aView,type:T.self)
        }

    }

    return nil
}

Call

let res = getGenericType(from: self.view,type:MyView.self)  // res of type MyView 
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87