案例如何在 if-case 中工作 [英] How case works in if-case

查看:30
本文介绍了案例如何在 if-case 中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一位老 C 程序员可以在 Swift 方面得到一些帮助.

An old C programmer could use some help with Swift.

我不了解 if-case 语法.例如:

I don't understanding something about the if-case syntax. E.g.:

if case 20...30 = age {
   print ("in range.")
}

case 20...30 = age 似乎是 if 语句的条件测试.因此,最初看到使用赋值运算符 ('=') 而不是比较运算符 ('==') 时,我感到很困惑.

The case 20...30 = age appears to be the conditional test for the if statement. So I was initially confused to see the assignment operator ('=') used instead of a comparison operator ('==').

好吧,我心里想,这可能意味着 case 语句实际上是一个返回布尔值的函数调用.返回的值将满足 if 语句中的比较测试.

Ok, I thought to myself, that probably means the case statement is actually a function call that returns a boolean value. The returned value will then satisfy the comparison test in the if statement.

作为一项实验,我尝试将 case 语句视为常规条件测试并在其周围放置括号.Swift 很乐意接受 if (x == 5)if (true).但是 if (case 20...30 = age) 会产生错误.所以 case 语句似乎不像函数.

As an experiment, I tried treating the the case statement like a regular conditional test and placed parentheses around it. Swift will happily accept if (x == 5) or if (true). But if (case 20...30 = age) generates an error. So the case statement doesn't seem to behave like function.

我只是想知道这里发生了什么.任何见解将不胜感激.

I'm just curious to understand what's happening here. Any insight would be greatly appreciated.

推荐答案

操作符是if case,所以不能加括号.语法和行为基于 Swift switch 语句中的 case 语句(参见 我的在线书籍(如果您需要详细信息).在case语句中,20...30是一个区间,用作pattern,使用contains进行操作代码>针对间隔.等号确实确实令人困惑,但这是他们第一次尝试使用语法来表达 case 语句应该与之比较的内容(即 tag 之后的 switch 语句中的 code>switch 关键字).

The operator is if case, so you can't put parentheses. The syntax and behavior are based on those of the case statement in a Swift switch statement (see my online book if you need details). In a case statement, 20...30 is an interval, used as a pattern, which operates by using contains against the interval. The equals sign is indeed truly confusing, but that was their first attempt at a syntax for expressing what the case statement should be comparing with (i.e. the tag that comes after the switch keyword in a switch statement).

所以,如果你明白这一点:

So, if you understand this:

switch age {
case 20...30:
    // do stuff
default:break
}

...然后你就明白它是如何直接变成这样的:

... then you understand how it is morphed directly into this:

if case 20...30 = age {
   // do stuff
}

这篇关于案例如何在 if-case 中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆