Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 案例(let name,let x)_Swift_Switch Statement - Fatal编程技术网

Swift 案例(let name,let x)

Swift 案例(let name,let x),swift,switch-statement,Swift,Switch Statement,你好,我正在做一些基本的快速练习。这个是切换语句。我已经到处找了好几天了,但是不能完全得到这个代码的正确解释 let tuple = ("Matt", 30) switch (tuple) { case (let name, let x) where x >= 0 && x <= 2: print("\(name) is a infant") case (let name, let x) where x >= 3 && x <= 12:

你好,我正在做一些基本的快速练习。这个是切换语句。我已经到处找了好几天了,但是不能完全得到这个代码的正确解释

let tuple = ("Matt", 30)
switch (tuple) {
case (let name, let x) where x >= 0 && x <= 2:
  print("\(name) is a infant")
case (let name, let x) where x >= 3 && x <= 12:
  print("\(name) is a child")
case (let name, let x) where x >= 13 && x <= 19:
  print("\(name) is a teenager")
case (let name, let x) where x >= 20 && x <= 39:
  print("\(name) is an adult")
case (let name, let x) where x >= 40 && x <= 60:
  print("\(name) is a middle aged")
case (let name, let x) where x >= 61:
  print("\(name) is a elderly")
default:
  print("Invalid age")
这里到底发生了什么?这个名字怎么指“马特”?为什么不多输入一些代码来创建一个名为“Matt”的字符串呢?像这样:

let name = "Matt"
还有,let x部件是怎么回事?是否使用常数:

let tuple = ("Matt", 30)
让计算机知道Switch语句中已经有字符串和Int?因此,无论何时使用任何字符串,它都将引用“Matt”?就像我们要做这样的事情:

case(let dog, let z) 
为什么这和“让名字,让x”不一样呢


“x”与30有什么关系?据我所知,“x”将是一个字符串,但它被视为一个整数。

开关
语句中,您设置了
元组
,其中包含一个字符串
Matt
和整数
30
case
将变量
name
age
设置为这些值,并仅比较
age


您可以使用任何变量名称,因此您的
将是名称,
z
将是年龄。编译器不关心名称,只要元组有适当数量的名称

元组只是一个携带多个值的变量。在您的示例中,元组的类型是
(String,Int)
,因为这是您最初定义它的方式

就像在执行
let name=“Matt”
操作时,除了字符串旁边有一个
Int
之外,这只是在执行该操作

然后开关根据模式匹配检查该元组

(let name,let x)
只是从该元组中获取值,并将它们插入名为
name
x
的变量中,以便使用它们。如果没有此选项,您将无法在代码中打印姓名或年龄

如果你不在乎名字,你可以

case (_, let x):
print("This person is \(x) years old")
无法在此处打印该名称,因为尚未将其放入变量名中

你也可以做
案例(让狗,让z):
。这将起作用,现在变量
dog
将是一个值为“Matt”的
字符串。但这样做没有意义,因为该值是一个名称,而不是一只狗。:-)

如果你的第一句话是

let tuple = ("Oliver", 33)

然后名称变量将是“Oliver”,X将是33。

感谢您的回复!谢谢你的回答,你的回答为我澄清了问题。
let tuple = ("Oliver", 33)