I have a collection of LayoutElement that I receive from an API.
For simplicity sake, imagine it contains 2 properties -
String or [LayoutElement]
I'd like to iterate over this collection and if the value has children, loop over the children recursively, returning the LayoutElement that contains a String
Essentially I should end up with a [LayoutElement] that contains only the elements that have a String value.
As this will be used in multiple places, I thought I could create an extension on Array where the element is LayoutElement but I am unsure how best to do this in the case of element.children.
import UIKit
struct LayoutElement {
let children: [LayoutElement]?
let text: String?
}
let data = [
LayoutElement(children: nil, text: "First Text Element"),
LayoutElement(children: [
LayoutElement(children: nil, text: "Second Text Element"),
LayoutElement(children: nil, text: "Third Text Element"),
LayoutElement(children: [
LayoutElement(children: nil, text: "Fourth Text Element"),
], text: nil)
], text: nil),
]
extension Array where Element == LayoutElement {
var asLayout: [LayoutElement] {
return map { element in
if let children = element.children {
// ???
} else {
return element
}
}
}
}
let output = data.asLayout
print(output)