Skip to content

Instantly share code, notes, and snippets.

@eonist
Last active August 31, 2020 01:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eonist/9bf74542b9ffc6e98d6e9321fb9ae262 to your computer and use it in GitHub Desktop.
Save eonist/9bf74542b9ffc6e98d6e9321fb9ae262 to your computer and use it in GitHub Desktop.
ViewController descendants
extension UIViewController {
/**
* Traverses the entire VC hirearchy downwards and collects VC'w that are of speccific PARAM: type
* - Fixme: ⚠️️ this can be written more elegantly with flatMap
* ## Example:
* let vc: CustomVC? = UIApplication.shared.delegate?.window?.rootViewController?.descendants().first
*/
func descendants<T>(type: T.Type? = nil) -> [T] {
var childrenOfType: [T] = []
self.children.forEach {
if let child: T = ($0 as? T) {
childrenOfType.append(child)
}
if !$0.children.isEmpty {
childrenOfType += $0.descendants(type: type)
}
}
return childrenOfType
}
}
@jaouahbi
Copy link

jaouahbi commented Mar 6, 2020

Must be "return childrenOfType" instead "return subViewsOfType"

@eonist
Copy link
Author

eonist commented Mar 7, 2020

Fixed. Thanks 👍

@League2EB
Copy link

@eonist
i find the this issues on my case

@eonist
Copy link
Author

eonist commented Aug 31, 2020

Put let vc: UIViewConteoller in front or cast AS VC

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment