🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
可以捕获一个子模式的任何值,通过匹配它对应的一个标识符: > It is possible to catch any value of a sub-pattern by matching it against an identifier: ~~~ var myTree = Node(Leaf("foo"), Node(Leaf("bar"), Leaf("foobar"))); var name = switch(myTree) { case Leaf(s): s; case Node(Leaf(s), _): s; case _: "none"; } trace(name); // foo ~~~ 这会返回如下之一: > This would return one of the following: * 如果 myTree 是一个 Leaf,它的name 被返回 * 如果myTree 是一个 Node,并且左侧的子树是一个 Leaf,它的name被返回(这应用在这里,返回“foo”) * 否则 “none”被返回 > * If myTree is a Leaf, its name is returned. > * If myTree is a Node whose left sub-tree is a Leaf,its name is returned (this will apply here, returning "foo"). > * Otherwise "none" is returned. 还可以使用 = 来捕获值,这更进一步的匹配: > It is also possible to use = to capture values which are further matched: ~~~ var node = switch(myTree) { case Node(leafNode = Leaf("foo"), _): leafNode; case x: x; } trace(node); // Leaf(foo) ~~~ 这里 ,如果输入匹配 leafNode 是绑定到 Leaf("foo") 。在所有其他情况,myTree 本身是被返回:case x 工作方式类似于 case \_ ,它匹配任何,但是使用一个i额标识名称如 x ,它也会绑定匹配的值到这个变量。 > Here, leafNode is bound to Leaf("foo") if the input matches that. In all other cases, myTree itself is returned: case x works similar to case \_ in that it matches anything, but with an identifier name like x it also binds the matched value to that variable.