'Views at depth with root view - recursive?
I am trying to write a function to return all children of a view at a given depth :
/// Write the body of the function `views(atDepth:withRootView:)`
/// which should return all children of a view at a given depth.
/// Example of a view hierarchy:
///
/// 0: view1
/// |
/// 1: view2
/// |
/// 2: view3
/// / \
/// 3: view4 view5
/// | |
/// 4: view6 view7
/// |
/// 5: view8
///
/// Expected results for some calls with the hierarchy above:
/// `views(atDepth: 0, withRootView: view1) == [view1]`
/// `views(atDepth: 1, withRootView: view1) == [view2]`
/// `views(atDepth: 2, withRootView: view1) == [view3]`
/// `views(atDepth: 3, withRootView: view1) == [view4, view5]`
/// `views(atDepth: 4, withRootView: view1) == [view6, view7]` <-- The final boss test
/// `views(atDepth: 5, withRootView: view1) == [view8]`
This is what I wrote (and it's working) :
func views(atDepth depth: Int, withRootView rootView: UIView, currentRecursiveLevel:Int? = 0) -> [UIView] {
var arr = [UIView]()
if depth == 0 || currentRecursiveLevel == depth {
arr.append(rootView)
} else {
for subview in rootView.subviews {
arr.append(contentsOf: views(atDepth: depth, withRootView: subview, currentRecursiveLevel: currentRecursiveLevel! + 1))
}
}
return arr
}
Can I (and how to ?) remove the parameter currentRecursiveLevel to have this definition :
func views(atDepth depth: Int, withRootView rootView: UIView) -> [UIView]
Solution 1:[1]
Solution provided by MrSmith42 :
func views(atDepth depth: Int, withRootView rootView: UIView) -> [UIView] {
if depth == 0 {
return [rootView]
} else {
var arr = [UIView]()
for subview in rootView.subviews {
arr.append(contentsOf: views(atDepth: depth - 1, withRootView: subview))
}
return arr
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Thomas Mary |
