English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Swift switch 문

在本文中,您将学习使用switch控制语句来控制程序执行的流程。

switch语句也是多种Swift控制语句,例如if-elseguard等,它们根据不同的条件执行不同的动作。

switch语句的优点在于,它可以将值与几种可能的匹配模式进行比较。 因此,它可以代替长if..else..if梯形图,同时匹配复杂模式。

switch语句的语法

switch语句的语法为:

switch 变量/表达式 {
case value1:
	// 语句
case value2:
	// 语句
case
	// 语句
}

Swift中的Switch语句如何工作?

  • switch 表达式只计算一次。

  • 它接受表达式并按顺序(上->下)与每个case值进行比较。

  • 如果存在匹配项,则执行 case 内的语句,并且第一个匹配的 switch case 一旦完成,整个switch语句就结束执行。

  • 如果没有匹配的case,则落到下一个case语句。

  • 如果都没有匹配到case,则default关键字指定要运行的代码。

注意:每个 case 的主体必须至少包含一个可执行语句。

의 문장 print("Thursday")는 cas와 switch 표현식이 일치하지 않아도 실행됩니다. 따라서, 컨솔에서도 Thursday 출력을 볼 수 있습니다.1:使用Switch语句的简单程序

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

위 프로그램을 실행하면, 출력은 다음과 같습니다:

default:

在上面的程序中,switch语句通过将dayOfWeek值与 print("Thursday") 1匹配来开始。由于dayOfWeekvalue与第一种情况的值不匹配,因此它会降到下一种情况,直到其中一个匹配。

由于print("Thursday") 4与switch表达式匹配,因此case内部的 print("Wednesday") 语句将被执行,并且switch case终止。如果没有case匹配,则执行default内部的语句。

의 문장 print("Thursday")는 cas와 switch 표현식이 일치하지 않아도 실행됩니다. 따라서, 컨솔에서도 Thursday 출력을 볼 수 있습니다.2:带 fallthrough 的 Switch 语句

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

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

위 프로그램을 실행하면, 출력은 다음과 같습니다:

default:
print("Invalid day")

Wednesday 4 Thursday 5위 프로그램에서는 case 5print("Wednesday")을 실행하면, fallthrough 키워드가 case를 계속 실행합니다.

의 문장 print("Thursday")는 cas와 switch 표현식이 일치하지 않아도 실행됩니다. 따라서, 컨솔에서도 Thursday 출력을 볼 수 있습니다.3.case

:가장 복잡한 패턴의 switch 문 10)
예제
	let programmingLanguage = (name: "Go", version:
		switch programmingLanguage {
	case (let name, let version) where (version < 0 && name.count < 0) : 4:
		print("잘못된 입력입니다")
	case ("Swift", let version) where version ==4 ) :
		print("오래된 버전의 Swift를 찾았습니다")
	case ("Swift",4... :
		print("Swift 버전이 큽니다")4아직 출시되지 않았습니다)
	case ("Taylor Swift",30) :
		print("하늘을 볼 것 같아요. 이는 테일러 스위프트입니다")
	case (let name, let version):  
		print("""
			프로그래밍 언어: (name)
			버전: (version)
			상태: Not found
		""")
}

위 프로그램을 실행하면, 출력은 다음과 같습니다:

프로그래밍 언어: Go
버전: 10
상태: Not found

위 프로그램에서는 튜플 타입의 표현식 programmingLanguage를 다음과 같은 다른 경우와 일치시킵니다:

  • case (let name, let version) where (version < 0 && name.count < 0)
    이 예제에서는 switch 표현식 값이 일시적 상수나 변수에 바인딩되어 let 키워드를 사용하여 대소문자로 사용할 수 있도록 합니다. 이를 값 바인딩이라고 합니다.
    where 절을 사용하여 이러한 값에 조건을 적용할 수도 있습니다. 여러 조건을 연결할 수 있으며, 예제와 같이 && 연산자를 사용할 수 있습니다.
    where 절에서 정의된 조건을 만족하지 않는 경우, 이러한 case 블록의 문장은 실행되지 않으며 다음 switch case와 비교할 수 없습니다.

  • case ("Swift" , ..<4 )
    이 경우 튜플의 첫 번째 요소가 문자 리터럴 "Swift"과 일치하며, 두 번째 요소가 단방향 범위..<에 있는지 확인합니다4。

  • case ("Swift" ,4...)
    이 경우 튜플의 첫 번째 요소가 문자 리터럴 "Swift"과 일치하며, 두 번째 요소가 단방향 범위에 있는지 확인합니다4...。

  • case (let name, let version)
    이 경우 튜플의 각 값이 일시적인 상수나 변수에 바인딩됩니다.