ios - 扩展保存特定元素类型的快速数组

标签 ios swift swift2

我一直在尝试扩展一个包含特定类型的 swift 数组。

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)
 }
}

上面的代码不会被编译,因为“节点”不是“元素”的子类型,即使我正在扩展元素“节点”的数组。 我怎样才能 swift 存档我想在这里做的事情? 我正在尝试向 [Node] 添加实例方法以展开 self 。

最佳答案

问题是协议(protocol) Node 不符合自身:Node 不是 Node 类型(听起来很矛盾),因为协议(protocol)不是具体类型,它只是对符合类型的要求。

也就是说,您需要将代码中的每个 Node 实例替换为 Element,然后它应该可以工作(现在无法测试)。这是因为,您实际上不是在处理某些 Node 类型的值,而是处理符合 Node (Element > 在你的情况下)

此外,您在代码中还犯了其他一些错误,我会把它留给其他人来更正,因为我没时间了。

关于ios - 扩展保存特定元素类型的快速数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32957244/

相关文章:

ios - 如何检测是否正在为 Swift 中的设备或模拟器构建应用程序

iphone - 弱链接 iPhone 应用程序的多个框架 (-weak_framework)

ios - 避免用户注册系统,但需要应用内购买和数据同步

swift - SceneKit - 运动 + 重力 = 奇怪的运动

xcode - 错误 : Use of unresolved identifier 'kCGBlendModeMultiply'

swift - 有没有办法定义一个幂为 2(或计算值)的快速枚举

ios subview 不响应触摸事件

ios - 滚动 UICollectionView 以响应键盘通知

ios - Swift 支持 WebRTC 吗?

ios - "Cannot override ' init ' which has been marked unavailable"防止覆盖空 init