基本用法

let number = 3
switch number {
case 1:
    print("One!")
case 2:
    print("Two!")
case 3:
    print("Three!")
default:
    print("Not One, Two or Three")
}

switch 語句也適用於整數以外的資料型別。它們適用於任何資料型別。這是一個開啟字串的示例:

let string = "Dog"
switch string {
case "Cat", "Dog":
  print("Animal is a house pet.")
default:
  print("Animal is not a house pet.")
}

這將列印以下內容:

Animal is a house pet.