Swift switch 语句

switch 语句允许我们在许多备选项中执行一个代码块。

Swift 中 switch 语句的语法是

switch (expression)  {
  case value1:
    // statements 

  case value2:
    // statements 

  ...
  ...
        
  default:
    // statements
}

switch 语句计算括号 () 内的表达式。

  1. 如果表达式的结果等于 value1,则执行 case value1: 的语句。
  2. 如果表达式的结果等于 value2,则执行 case value2: 的语句。
  3. 如果没有匹配项,则执行 **default case** 的语句。

注意: 我们可以使用 if...else...if 阶梯来实现相同的功能。但是,switch 语句的语法更简洁,更易于阅读和编写。


Switch Statement 的流程图

Switch statement allows us to execute certain code blocks out of many alternatives.
Switch Statement 的流程图

示例 1:使用 Switch 语句的简单程序

// program to find the day of the week 

let dayOfWeek = 4

switch dayOfWeek {
  case 1:
    print("Sunday")
	    
  case 2:
    print("Monday")
	    
  case 3:
    print("Tuesday")
	    
  case 4:
    print("Wednesday")
	    
  case 5:
    print("Thursday")
	    
  case 6:
    print("Friday")
	    
  case 7:
    print("Saturday")
	    
  default:
    print("Invalid day")
}

输出

Wednesday

在上面的示例中,我们将 4 赋值给 dayOfWeek 变量。现在,变量会与每个 case 语句的值进行比较。

由于该值与 case 4 匹配,因此执行 case 中的语句 print("Wednesday"),程序终止。


带有 fallthrough 的 Switch 语句

如果在 case 语句中使用 fallthrough 关键字,即使 case 值与 switch 表达式不匹配,控制也会继续到下一个 case。例如,

// program to find the day of the week 

let dayOfWeek = 4

switch dayOfWeek {
  case 1:
    print("Sunday")
	    
  case 2:
    print("Monday")
	    
  case 3:
    print("Tuesday")
	    
  case 4:
    print("Wednesday")
    fallthrough
	    
  case 5:
    print("Thursday")
	    
  case 6:
    print("Friday")
	    
  case 7:
    print("Saturday")
	    
  default:
    print("Invalid day")
}

输出

Wednesday
Thursday

在上面的示例中,由于该值与 case 4 匹配,因此执行 case 中的语句 print("Wednesday")

我们还使用了 fallthrough 关键字。因此,即使 case 不匹配 case 语句,case 5 中的语句 print("Thursday") 也会被执行。


示例 2:带有范围的 Switch 语句

let ageGroup = 33

switch ageGroup {
  case 0...16:
    print("Child")

  case 17...30:
    print("Young Adults")

  case 31...45:
    print("Middle-aged Adults")

  default:
    print("Old-aged Adults")
}

输出

Middle-aged Adults

在上面的示例中,我们为每个 case 使用了数字范围,而不是单个值:case 0...16case 17...30case 31...45

这里,ageGroup 的值为 33,落在范围 32...45 内。因此,执行语句 print("Middle-aged Adults")


Switch 语句中的元组

在 Swift 中,我们也可以在 switch 语句中使用 元组。例如,

let info = ("Dwight", 38)

// match complete tuple values
switch info {
  case ("Dwight", 38): 
    print("Dwight is 38 years old")

  case ("Micheal", 46): 
    print("Micheal is 46 years old")

  default:
    print("Not known")
}

输出

Dwight is 38 years old

在上面的示例中,我们创建了一个名为 info 的元组,值为:"Dwight"38

这里,每个 case 语句不仅包含单个值,还包含元组:case ("Dwight", 38)case ("Micheal", 46)

现在,info 的值与每个 case 语句进行比较。由于该值与 case ("Dwight", 38) 匹配,因此执行语句 print("Dwight is 38 years old")

要了解有关元组的更多信息,请访问 Swift 元组

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战