深入讲解Swift中的模式匹配

2020-01-09 00:19:03王旭

Switch 中的模式匹配

Switch 中的模式匹配也很常用,在 Switch 中合理地使用模式匹配可以为我们带来很多好处,可以使我们的代码更简洁,同时可以减少代码量和增加开发效率。

区间匹配


let value = 188

switch value {
case 0..<50:
 print("The value is in range [0, 50)")
case 50..<100:
 print("The value is in range [50, 100)")
case 100..<150:
 print("The value is in range [100, 150)")
case 150..<200:
 print("The value is in range [150, 200)")
case 200...:
 print("The value is in range [200, ")
default: break
}

// The value is in range [150, 200)

匹配元组类型

创建一个元组类型:


let tuples: (Int, String) = (httpCode: 404, status: "Not Found.")

进行匹配:


switch tuples {
case (400..., let status):
 print("The http code is 40x, http status is (status)")
default: break
}

创建一个点:


let somePoint = (1, 1)

进行匹配:


switch somePoint {
case (0, 0):
 print("(somePoint) is at the origin")
case (_, 0):
 print("(somePoint) is on the x-axis")
case (0, _):
 print("(somePoint) is on the y-axis")
case (-2...2, -2...2):
 print("(somePoint) is inside the box")
default:
 print("(somePoint) is outside of the box")
}

如上,我们在匹配的时候可以使用下划线 _ 对值进行忽略:


switch tuples {
case (404, _):
 print("The http code is 404 not found.")
default: break
}