Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Description that can be used with any type that has recursive children
public protocol HierarchyDescription {
associatedtype Child: HierarchyDescription
var children: [Child] { get }
var description: String { get }
}
extension HierarchyDescription {
public var hierarchyDescription: String {
var description = self.description
for child in children {
description += "\n " + child.hierarchyDescription
.replacingOccurrences(of: "\n", with: "\n ")
}
return description
}
}
extension HierarchyDescription where Self == Child {
public func hierarchyDescription(customDescription: (Self) -> String = \.description) -> String {
var description = customDescription(self)
for child in children {
description += "\n " + child.hierarchyDescription(customDescription: customDescription)
.replacingOccurrences(of: "\n", with: "\n ")
}
return description
}
public var allChildren: [Child] {
children + children.flatMap { $0.allChildren }
}
}
extension UIView: HierarchyDescription {
public var children: [UIView] { subviews }
}
let datePicker = UIDatePicker()
print(datePicker.hierarchyDescription)
//<UIDatePicker: 0x7f9f35f580c0; frame = (0 0; 221.667 34.3333); layer = <CALayer: 0x600000862c40>>
// <_UIDatePickerIOSCompactView: 0x7f9f35f58280; frame = (0 0; 0 0); gestureRecognizers = <NSArray: 0x60000028d410>; layer = <CALayer: 0x600000862800>>
// <UIView: 0x7f9f35f57f30; frame = (0 0; 0 0); layer = <CALayer: 0x6000008625e0>>
// <UIView: 0x7f9f35f584a0; frame = (0 0; 0 0); layer = <CALayer: 0x600000862840>>
// <_UIDatePickerLinkedLabel: 0x7f9f35f58610; frame = (0 0; 0 0); layer = <CALayer: 0x600000862880>>
// <UILabel: 0x7f9f35f589d0; frame = (0 0; 0 0); text = '11/30/20'; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x600002ef63f0>>
// <UIView: 0x7f9f35f592d0; frame = (0 0; 0 0); layer = <CALayer: 0x6000008628a0>>
// <UIView: 0x7f9f35f59440; frame = (0 0; 0 0); layer = <CALayer: 0x600000862940>>
// <UILabel: 0x7f9f35f595b0; frame = (0 0; 0 0); text = '12:11 PM'; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x600002ef6760>>
print((datePicker as UIView).allChildren.last)
//<UILabel: 0x7f9f35f595b0; frame = (0 0; 0 0); text = '12:11 PM'; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x600002ef6760>>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment