模式匹配第四弹:if case,guard case,for case

2023-03-14,,

2016-06-06 7388

作者:Olivier Halligon,原文链接,原文日期:2016-05-16

译者:walkingway;校对:Cee;定稿:numbbbbb

现在我们来重新回顾下前三弹模式匹配的各种语法 第一弹,第二弹,第三弹,第四弹是本系列的最后一篇文章,本章会教大家使用 if case let,for case where 等一些高级语法,让我们拭目以待吧!

本篇文章会结合本系列前三篇文章提到的语法,然后将它们应用在一些更先进表达式中。

这篇文章是模式匹配系列文章的最后一部分,你可以在这里阅读所有内容:第一弹,第二弹,第三弹,第四弹

if case let

语句 case let x = y 模式允许你检查 y 是否能匹配 x。

而 if case let x = y { … } 严格等同于 switch y { case let x: … }:当你只想与一条 case 匹配时,这种更紧凑的语法尤其有用。有多个 case 时更适合使用 switch。

例如,我们有一个与之前文章类似的枚举数组:

casecasecase然后我们可以这样写:

m = Media.Movie(title: , director: , year: )

Media.Movie(title, , ) = m {

print"This is a movie named \(title)"改用 switch 后更冗长的版本:

m {

caselet__print"This is a movie named \(title)"default// do nothing, but this is mandatory as all switch in Swift must be exhaustive

if case let where

我们当然还可以将 if case let 和 where 从句组合在一起用:

Media.Movie(, , year) = m year < {

print"Something seems wrong: the movie's year is before the first movie ever made."这种方式可以组合成一个相当强大的表达式,而改用 switch 实现可能会变得非常复杂,需要写很多行代码来检测那一个特定的 case。

guard case let

当然,guard case let 类似于 if case let,你可以使用 guard case let 和 guard case let … where … 来确保匹配一个模式或一个条件,而当无法匹配模式或满足条件时就退出。

casecase

(response: NetworkResponse)guardcaseletletaswhere200300elseprint"Invalid response, can't process"return

}

print"Processing \(data.length) bytes…"/* … */

for case

将 for 和 case 组合在一起也能让你有条件地遍历一个集合对象。使用 for case … 语义上类似于 for 循环,而且将它整个循环体封装在了 if case 的结构之中:它只会遍历、处理那些模式匹配了的元素。

mediaList: [Media] = [

"Harry Potter and the Philosopher's Stone""J.K. Rowling"1997"Harry Potter and the Philosopher's Stone""Chris Columbus"2001"Harry Potter and the Chamber of Secrets""J.K. Rowling"1999"Harry Potter and the Chamber of Secrets""Chris Columbus"2002"Harry Potter and the Prisoner of Azkaban""J.K. Rowling"1999"Harry Potter and the Prisoner of Azkaban""Alfonso Cuarón"2004"J.K. Rowling: A Year in the Life""James Runcie"2007"https://en.wikipedia.org/wiki/List_of_Harry_Potter-related_topics"

()

Media.Movie(title, , year) mediaList {

print" - \(title) (\(year))"

- Harry Potter and the Philosopher's Stone (2001)

- Harry Potter and the Chamber of Secrets (2002)

- Harry Potter and the Prisoner of Azkaban (2004)

- J.K. Rowling: A Year in the Life (2007)

for case where

为 for case 增加一个 where 从句,能使其变得更加强大:

()

Media.Movie(title, director, year) mediaList director == {

print" - \(title) (\(year))"

- Harry Potter and the Philosopher's Stone (2001)

- Harry Potter and the Chamber of Secrets (2002)

模式匹配第四弹:if case,guard case,for case的相关教程结束。

《模式匹配第四弹:if case,guard case,for case.doc》

下载本文的Word格式文档,以方便收藏与打印。