I've been trying to extend a swift array that hold specific type.
protocol Node {
var nodeId: Int { get }
var parentId: Int? { get }
var children: [Node] { get set }
var level: Int { get set }
}
extension Array where Element : Node {
/**
unflatten an array of Nodes.
*/
func unflattenNodes()-> [Node] {
func unflatten(inout parent: Node?)-> [Node] {
var topNodes = [Node]()
let children = self.filter{ (child: Node) in return child.parentId == parent?.nodeId ?? 0 }
if !children.isEmpty {
if var parent = parent {
for var child in children {
child.level = parent.level + 1
}
parent.children = children
}
else {
topNodes = children
}
for child in children {
var optChild = Optional(child)
unflatten(&optChild)
}
}
return topNodes;
}
var optChild: Node? = nil
return unflatten(&optChild)
}
}
This code above won't be compiled because 'Node' is not subtype of 'Element', even though I'm extending Array of element "Node". How can I archive what I'm trying to do here in swift? I'm trying to add an instance method to [Node] to unflatten self.