小编Kua*_*hou的帖子

Swift中使用泛型的递归枚举

我是Swift的新手.我试图用递归枚举和泛型实现二叉树:

enum BinaryTree<T> {
  indirect case Node(T, BinaryTree<T>, BinaryTree<T>)
  case Nothing
}

func inorder<T>(_ root: BinaryTree<T>) -> [T] {
  switch root  {
  case .Nothing: 
    return []
  case let .Node(val, left, right):
    return inorder(left) + [val] + inorder(right) 
  }
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:

$ swift ADT.swift 
ADT.swift:83:20: error: cannot convert value of type 'BinaryTree<T>' to expected argument type 'BinaryTree<_>'
    return inorder(left) + [val] + inorder(right) 
                   ^~~~
Run Code Online (Sandbox Code Playgroud)

但是,这有效:

func inorder<T>(_ root: BinaryTree<T>) -> [T] {
  switch root  {
  case .Nothing: 
    return []
  case let …
Run Code Online (Sandbox Code Playgroud)

recursion enums swift

5
推荐指数
1
解决办法
131
查看次数

标签 统计

enums ×1

recursion ×1

swift ×1