swift switch case 的复杂用法

发布时间 2023-09-11 11:05:01作者: 漫思

Swift 中的 switch 语句非常灵活,可以用于处理各种复杂的条件。下面是一些 switch 语句的复杂用法:

  1. 匹配值和范围: 你可以使用 case 子句来匹配特定的值,也可以匹配一个值范围。例如:
swiftlet number = 3

switch number {
case 1:
print("Number is 1")
case 2, 3, 4:
print("Number is 2, 3, or 4")
case let 5..<10:
print("Number is between 5 and 10")
default:
print("Number is not between 1 and 10")
}

在这个例子中,case let 5..<10: 匹配了5到9之间的任何数字。 2. 匹配值的数组: 你可以使用数组中的值作为 case 的参数。例如:

swiftlet fruit = "apple"

switch fruit {
case ["banana", "apple"]:
print("This is a banana or an apple")
default:
print("This is not a banana or an apple")
}

在这个例子中,case ["banana", "apple"]: 匹配了数组 ["banana", "apple"] 中的任何元素。 3. 匹配值的集合: 你也可以使用集合(Set)中的值作为 case 的参数。例如:

swiftlet fruit = "apple"

switch fruit {
case Set([ "banana", "apple"]):
print("This is a banana or an apple")
default:
print("This is not a banana or an apple")
}

在这个例子中,case Set([ "banana", "apple"]): 匹配了集合 Set([ "banana", "apple"]) 中的任何元素。 4. 匹配值的元组: 你可以使用元组中的值作为 case 的参数。例如:

swiftlet (x, y) = (2, 3)

switch (x, y) {
case (1, _):
print("x is 1")
case (_, 2):
print("y is 2")
case (1, 2):
print("x is 1 and y is 2")
default:
print("None of the above")
}

在这个例子中,case (1, _): 匹配了元组中第一个元素为1的情况,case (_, 2): 匹配了元组中第二个元素为2的情况,以此类推。在 case (1, 2): 中,两个元素都被明确地进行了匹配。