Swift中使用泛型的递归枚举
发布时间:2020-12-14 04:56:13 所属栏目:百科 来源:网络整理
导读:我是 Swift的新手.我试图用递归枚举和泛型实现二叉树: enum BinaryTreeT { indirect case Node(T,BinaryTreeT,BinaryTreeT) case Nothing}func inorderT(_ root: BinaryTreeT) - [T] { switch root { case .Nothing: return [] case let .Node(val,left,rig
我是
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) } } 这是我得到的错误: $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) ^~~~ 但是,这有效: func inorder<T>(_ root: BinaryTree<T>) -> [T] { switch root { case .Nothing: return [] case let .Node(val,right): let l = inorder(left) let r = inorder(right) return l + [val] + r } } 我的语法有错吗?谢谢! 我正在使用Swift 3.0. 解决方法
更新
所以我试着将问题压缩成最小的示例代码,无法编译,asked a question我自己并提交了 SR-4304.结果答案是,这确实是编译器中的一个错误. 原始答案 return (inorder(left) as [T]) + [val] + inorder(right) return Array([inorder(left),[val],inorder(right)].joined()) return [inorder(left),inorder(right)].reduce([],+) return [inorder(left),inorder(right)].flatMap { $0 } func myjoin1<T>(_ arrays: [T]...) -> [T] { return arrays.reduce([],+) } return myjoin1(inorder(left),inorder(right)) func myjoin2<T>(_ array1: [T],_ array2: [T],_ array3: [T]) -> [T] { return array1 + array2 + array3 } return myjoin2(inorder(left),inorder(right)) extension Array { func appending(_ array: [Element]) -> [Element] { return self + array } } return inorder(left).appending([val]).appending(inorder(right)) 将操作符作为函数调用也会编译: return (+)(inorder(left),[val]) + inorder(right) 如果对Swift编译器有更深入了解的人可以对此有所了解,那就太好了. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |