将 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 == {