📜  Swift – Switch 语句

📅  最后修改于: 2022-05-13 01:54:28.326000             🧑  作者: Mango

Swift – Switch 语句

在 Swift 中,switch 语句是一种控制机制,它允许程序更改其控制流并根据对变量值施加的某些条件做出某些决定。一旦满足匹配条件,程序的控制流就会从 switch 语句块中出来。如果不满足上述条件,它还提供默认条件。如果 switch 语句是详尽的,则 switch 语句中的默认语句是可选的。简单来说,只有当 switch 语句已经涵盖了所有可能的情况来处理变量的值时,我们才能跳过默认语句。如果 switch 语句没有涵盖所有可能的情况,同时跳过了默认语句,那么 Swift 编译器会抛出一个编译时错误。在程序中使用 switch 语句是一种很好的做法,应该在需要时使用。

句法:

流程图:

为什么要切换语句?

Switch 语句相当于一堆 if-else 语句。简而言之,我们可以在一堆 if-else 语句的帮助下完成与 switch 语句相同的任务。但是 switch 语句比 if-else 语句更有效,因为它们提高了代码的可读性。

例如,

让我们考虑一个场景,我们想根据一个字符对应的标记字符串打印一个字符串,

  • “A”->“苹果”
  • “B”->“男孩”
  • “C”->“猫”
  • “D”->“狗”

我们可以在 switch 语句的帮助下完成这项任务,如下所示:

Swift
// Swift program to illustrate the 
// working of switch statement
  
// Initializing a character
var myCharacter = "B"
  
// Switch block 
switch myCharacter 
{
      
    // If myCharacter is equal to "A"
    case "A":
      
        // Then print "Apple"
        print("Apple")
      
    // If myCharacter is equal to "B"
    case "B":
      
        // Then print "Apple"  
        print("Boy")
      
    // If myCharacter is equal to "C"  
    case "C":
      
        // Then print "Cat" 
        print("Cat")
      
    // If myCharacter is equal to "D"   
    case "D":
      
        // Then print "Dog"   
        print("Dog")
      
    // Default statement
    default:
        print("Invalid")
}


Swift
// Swift program to illustrate the working 
// of fallthrough statement in switch statement
  
// Initializing a character
var myCharacter = "B"
  
// Switch block 
switch myCharacter
{
      
    // If myCharacter is equal to "A"
    case "A":
      
        // Then print "Apple"
        print("Apple")
      
    // If myCharacter is equal to "B"
    case "B":
      
        // Then print "Apple"  
        print("Boy")
      
    // Using fallthrough so that
    // below case also gets executed
    fallthrough
      
    // If myCharacter is equal to "C"  
    case "C":
      
        // Then print "Cat" 
        print("Cat")
      
    // If myCharacter is equal to "D"   
    case "D":
      
        // Then print "Dog"   
        print("Dog")
      
    // Default statement
    default:
        print("Invalid")
}


Swift
// Swift program to illustrate 
// No implicit fallthrough
  
// Initializing a character
var myCharacter = "B"
  
// Switch block 
switch myCharacter 
{
      
    // If myCharacter is equal to "A"
    case "A":
      
        // Then print "Apple"
        print("Apple")
      
    // If myCharacter is equal to "B"
    case "B":
      
    // No body
      
    // If myCharacter is equal to "C"  
    case "C":
      
        // Then print "Cat" 
        print("Cat")
      
    // If myCharacter is equal to "D"   
    case "D":
      
        // Then print "Dog"   
        print("Dog")
      
    // Default statement
    default:
        print("Invalid")
}


Swift
// Swift program to illustrate the interval 
// matching in the switch statement
  
// Initializing an integer
var myInteger = 18
  
// Switch block 
switch myInteger 
{
      
    // If myInteger is equal to 2
    case 2:
      
        // Then print "Apple"
        print("Equal to 2")
      
    // If myInteger is between 3 and 5
    case 3..<5:
      
        // Then print "Between 3 and 5"  
        print("Between 3 and 5")
      
    // If myInteger is between 6 and 10  
    case 6..<10:
      
        // Then print "Between 6 and 10"  
        print("Between 6 and 10")
      
    // If myInteger is between 11 and 22
    case 11..<22:
      
        // Then print "Between 11 and 22"  
        print("Between 11 and 22")
      
    // Default statement
    default:
        print("Invalid")
}


Swift
// Swift program to illustrate the working
// of tuples with switch statement
  
// Initializing a tuple
var myTuple = (4, 10)
  
// Switch block 
switch myTuple 
{
  
    // If myTuple is equal to (2,3)
    case (2, 3):
      
        // Then print
        print("First case gets executed")
      
    // If myTuple is (between 1 and 3,between 5 and 11) 
    case (1...3, 5...11):
      
        // Then print  
        print("Second case gets executed")
      
    // If myTuple is (between 1 and 5, between 8 and 13)   
    case (1...5, 8...13):
      
        // Then print  
        print("Third case gets executed")
          
    // If myTuple is (between 11 and 13, between 15 and 18) 
    case (11...13, 15...18):
      
        // Then print  
        print("Fourth case gets executed")
      
    // Default statement
    default:
        print("Invalid")
}


Swift
// Swift program to illustrate the working 
// of value binding with switch statement
  
// Initializing a tuple
var myTuple = (2, 4, 6)
  
// Switch block 
switch myTuple 
{
  
    // If myTuple is equal to (2,3)
    case (let myElement1, 3, 6):
      
        // Then print
        print("myElement1 is equal to \(myElement1)")
      
    // If myTuple is (between 1 and 3, between 5 and 11) 
    case (let myElement1, let myElement2, 6):
      
        // Then print
        print("myElement1 is equal to \(myElement1)", 
              "myElement3 is equal to \(myElement2)")
      
    // If myTuple is (between 1 and 5, between 8 and 13)   
    case (let myElement1, let myElement2, let myElement3):
      
        // Then print
        print("myElement1 is equal to \(myElement1)", 
              "myElement1 is equal to \(myElement2)", 
              "myElement1 is equal to \(myElement3)")
      
}


Swift
// Swift program to illustrate the 
// working of where clause with switch statement
  
// Initializing a tuple
var myTuple = (20, 10)
  
// Switch block 
switch myTuple
{
  
    // If myElement1 is thrice of myElement2
    case let (myElement1, myElement2) where myElement1 == 3 * myElement2:
        
        // Then print
        print("myElement1 is thrice of myElement2")
      
    // If myElement1 is twice of myElement2
    case let (myElement1, myElement2) where myElement1 == 2 * myElement2:
       
        // Then print
        print("myElement1 is twice of myElement2")
      
    // If myElement1 is equal to myElement2
    case let (myElement1, myElement2) where myElement1 ==  myElement2:
      
        // Then print
        print("myElement1 is equal to myElement2")
      
    default:
      
        // Then print
        print("Invalid")
}


Swift
// Swift program to illustrate the compound cases
  
// Initializing a character
var myCharacter = "B"
  
// Switch block 
switch myCharacter
{
  
    // If myCharacter is equal to either "A" or "B"
    case "A", "B":
      
        // Then print "Either Apple or Boy"
        print("Either Apple or Boy")
      
    // If myCharacter is equal to "C"  
    case "C":
      
        // Then print "Cat" 
        print("Cat")
      
    // If myCharacter is equal to "D"   
    case "D":
      
        // Then print "Dog"   
        print("Dog")
      
    // Default statement
    default:
        print("Invalid")
}


输出:

Boy

失败声明

fallthrough 语句允许程序的控制流向下传递到下一个案例。无论是否匹配变量的值,都将执行下一个案例的主体。现在如果下一个案例也包含一个fallthrough语句,程序的控制流将传递到下一个案例的下一个,依此类推。否则,如果它不包含 fallthrough 语句,程序的控制流会立即从 switch 语句中出来。

句法:

例子:

迅速

// Swift program to illustrate the working 
// of fallthrough statement in switch statement
  
// Initializing a character
var myCharacter = "B"
  
// Switch block 
switch myCharacter
{
      
    // If myCharacter is equal to "A"
    case "A":
      
        // Then print "Apple"
        print("Apple")
      
    // If myCharacter is equal to "B"
    case "B":
      
        // Then print "Apple"  
        print("Boy")
      
    // Using fallthrough so that
    // below case also gets executed
    fallthrough
      
    // If myCharacter is equal to "C"  
    case "C":
      
        // Then print "Cat" 
        print("Cat")
      
    // If myCharacter is equal to "D"   
    case "D":
      
        // Then print "Dog"   
        print("Dog")
      
    // Default statement
    default:
        print("Invalid")
}

输出:

Boy
Cat

解释:由于myCharacter等于“B”,所以第二个案例的主体被执行。因为,我们在第二个案例的主体之后使用了 fallthrough 语句,所以第三个案例的主体也将被执行。请注意,虽然它不满足第三个条件(显然,“B”等于“C”),但第三种情况正在被执行。这表明 Swift 中的 fallthrough 语句有多么强大。

没有隐含的失败

在 switch 语句中,如果 case 条件不包含正文,则 Swift 编译器会产生编译时错误。这是因为 Swift 没有提供隐式的 fallthrough 语句来处理这种情况。

例子:

迅速

// Swift program to illustrate 
// No implicit fallthrough
  
// Initializing a character
var myCharacter = "B"
  
// Switch block 
switch myCharacter 
{
      
    // If myCharacter is equal to "A"
    case "A":
      
        // Then print "Apple"
        print("Apple")
      
    // If myCharacter is equal to "B"
    case "B":
      
    // No body
      
    // If myCharacter is equal to "C"  
    case "C":
      
        // Then print "Cat" 
        print("Cat")
      
    // If myCharacter is equal to "D"   
    case "D":
      
        // Then print "Dog"   
        print("Dog")
      
    // Default statement
    default:
        print("Invalid")
}

输出:

main.swift:18:5: error: 'case' label in a 'switch' should have at least one executable statement
    case "B":
    ^~~~~~~~~
              break

解释:在上述程序中, myCharacter等于“B”。虽然,我们有一个案例条件来处理这种情况,但它在主体中不包含任何可执行语句。

区间匹配

Swift 提供了一个功能,使用它我们可以在 switch 语句中使用区间匹配作为 case 条件。

句法:

case myValue1..

如果变量表达式的值介于 myValue1 和 myValue2 之间,则将执行上述案例的主体。

例子:

迅速

// Swift program to illustrate the interval 
// matching in the switch statement
  
// Initializing an integer
var myInteger = 18
  
// Switch block 
switch myInteger 
{
      
    // If myInteger is equal to 2
    case 2:
      
        // Then print "Apple"
        print("Equal to 2")
      
    // If myInteger is between 3 and 5
    case 3..<5:
      
        // Then print "Between 3 and 5"  
        print("Between 3 and 5")
      
    // If myInteger is between 6 and 10  
    case 6..<10:
      
        // Then print "Between 6 and 10"  
        print("Between 6 and 10")
      
    // If myInteger is between 11 and 22
    case 11..<22:
      
        // Then print "Between 11 and 22"  
        print("Between 11 and 22")
      
    // Default statement
    default:
        print("Invalid")
}

输出:

Between 11 and 22

元组匹配

在 Swift 中,元组用于将多个元素保存或组合在一起。元组中的元素可以是相同类型,也可以是不同类型。我们可以使用以下语法在 Swift 中初始化一个元组。

句法:

var myTuple = (myElement1, myElement2, . . . .)

Swift 为我们提供了一个功能,我们可以使用元组作为变量表达式以及 switch 语句中的 case 条件来测试多个值。元组的每个项目都根据不同的值进行检查。或者我们可以使用下划线字符(_) 来匹配可能的值。这里的下划线字符被称为通配符模式。

case (value1, value2,. . . .):
// Body of case
case(_, value1):
// Body of case

例子:

迅速

// Swift program to illustrate the working
// of tuples with switch statement
  
// Initializing a tuple
var myTuple = (4, 10)
  
// Switch block 
switch myTuple 
{
  
    // If myTuple is equal to (2,3)
    case (2, 3):
      
        // Then print
        print("First case gets executed")
      
    // If myTuple is (between 1 and 3,between 5 and 11) 
    case (1...3, 5...11):
      
        // Then print  
        print("Second case gets executed")
      
    // If myTuple is (between 1 and 5, between 8 and 13)   
    case (1...5, 8...13):
      
        // Then print  
        print("Third case gets executed")
          
    // If myTuple is (between 11 and 13, between 15 and 18) 
    case (11...13, 15...18):
      
        // Then print  
        print("Fourth case gets executed")
      
    // Default statement
    default:
        print("Invalid")
}

输出:

Third case gets executed

值绑定

Swift 允许我们在 switch 语句中的 case 条件中初始化一个临时变量,这个变量只能在它被初始化的 case 的主体中访问。此属性称为值绑定。

句法

case (let myElement1, let myElement2,..., let myElementN value1, value2, ...., valueN):
     // body

现在,如果 case 条件的所有常量值都与变量表达式的值匹配,则其余值将自动分配给相应的临时变量,并且将执行 case 的主体。

例子:

迅速

// Swift program to illustrate the working 
// of value binding with switch statement
  
// Initializing a tuple
var myTuple = (2, 4, 6)
  
// Switch block 
switch myTuple 
{
  
    // If myTuple is equal to (2,3)
    case (let myElement1, 3, 6):
      
        // Then print
        print("myElement1 is equal to \(myElement1)")
      
    // If myTuple is (between 1 and 3, between 5 and 11) 
    case (let myElement1, let myElement2, 6):
      
        // Then print
        print("myElement1 is equal to \(myElement1)", 
              "myElement3 is equal to \(myElement2)")
      
    // If myTuple is (between 1 and 5, between 8 and 13)   
    case (let myElement1, let myElement2, let myElement3):
      
        // Then print
        print("myElement1 is equal to \(myElement1)", 
              "myElement1 is equal to \(myElement2)", 
              "myElement1 is equal to \(myElement3)")
      
}

输出:

myElement1 is equal to 2 myElement3 is equal to 4

解释:在上面的程序中,因为myTuple等于 (2, 4, 6)。对于第一个 case 条件,由于 tuple 的第二个值不等于 myTuple 的第二个值,所以这个 case 的主体不会被执行。对于第二个case条件,由于元组的第三个元素等于myTuple的第三个值,所以第一个和第二个元素的值自动与case条件的第一个和第二个元素绑定。

将 where 子句与 switch 语句一起使用

Swift 还接受在 switch 语句中的 case 条件中的 where 子句,我们可以使用它来执行语句。或者我们可以说 where 子句用于检查额外或附加条件。

句法:

case let(myElement1, myElement2) where "condition":
     // body

例子:

迅速

// Swift program to illustrate the 
// working of where clause with switch statement
  
// Initializing a tuple
var myTuple = (20, 10)
  
// Switch block 
switch myTuple
{
  
    // If myElement1 is thrice of myElement2
    case let (myElement1, myElement2) where myElement1 == 3 * myElement2:
        
        // Then print
        print("myElement1 is thrice of myElement2")
      
    // If myElement1 is twice of myElement2
    case let (myElement1, myElement2) where myElement1 == 2 * myElement2:
       
        // Then print
        print("myElement1 is twice of myElement2")
      
    // If myElement1 is equal to myElement2
    case let (myElement1, myElement2) where myElement1 ==  myElement2:
      
        // Then print
        print("myElement1 is equal to myElement2")
      
    default:
      
        // Then print
        print("Invalid")
}

输出:

myElement1 is twice of myElement2

使用带有 switch 语句的复合案例

在 Swift 中,我们可以使用带有 switch 语句的复合案例。共享一个共同主体的案例条件可以使用逗号 ( , ) 组合在一起。或者我们可以说,当用逗号分隔的多个案例具有相同的主体时,这些案例称为复合案例。在复合情况下,如果任何模式与切换条件匹配,则该情况被认为是匹配的。需要时应遵循此技术,因为它可以减少代码大小并提高代码质量。

句法:

case condition1, condition2, ....:
    // body

例子:

迅速

// Swift program to illustrate the compound cases
  
// Initializing a character
var myCharacter = "B"
  
// Switch block 
switch myCharacter
{
  
    // If myCharacter is equal to either "A" or "B"
    case "A", "B":
      
        // Then print "Either Apple or Boy"
        print("Either Apple or Boy")
      
    // If myCharacter is equal to "C"  
    case "C":
      
        // Then print "Cat" 
        print("Cat")
      
    // If myCharacter is equal to "D"   
    case "D":
      
        // Then print "Dog"   
        print("Dog")
      
    // Default statement
    default:
        print("Invalid")
}

输出:

Either Apple or Boy