模式匹配第二弹:元组,range 和类型

Leslie_88 8年前
   <p>在<a href="http://www.open-open.com/lib/view/open1461650808637.html">上一篇文章</a>中,我们已经看过了使用 <code>switch</code> 来对枚举进行基本的模式匹配。那如果对除枚举外的其它类型使用 <code>switch</code>来进行模式匹配会怎样呢?</p>    <h2>对元组进行模式匹配</h2>    <p>在 Swift 当中,<code>switch</code> 并不像 ObjC 一样只能对整型或枚举进行匹配。</p>    <p>事实上,我们可以使用 <code>switch</code> 对很多类型进行匹配,包括(但不仅限于)元组。</p>    <p>这意味着我们只要将多个数据组合在一个元组中,就可以一次性匹配多个数据。比如说,如果你有一个 <code>CGPoint</code>,并且你想确定这个点是否位于某个坐标轴上,则可以使用 <code>switch</code> 来匹配它的 <code>.x</code> 和 <code>.y</code> 属性!</p>    <table>     <tbody>      <tr>       <td> <pre>  <code class="language-swift">let point = CGPoint(x: 7, y: 0)  switch (point.x, point.y) {    case (0,0): print("On the origin!")    case (0,_): print("x=0: on Y-axis!")    case (_,0): print("y=0: on X-axis!")    case (let x, let y) where x == y: print("On y=x")    default: print("Quite a random point here.")  }</code></pre> </td>      </tr>     </tbody>    </table>    <p>注意我们在上一篇文章中使用过的 <code>_</code> 通配符,以及第四个 <code>case</code> 使用到的 <code>(let x, let y)</code> 可以对变量进行绑定,然后使用 <code>where</code> 来检查它们是否相等。</p>    <h2>Case 是按顺序判断的</h2>    <p>还有一点要注意的是,<code>switch</code> 是按 <code>case</code> 模式被指定的顺序来判断求值的,并且它会在匹配到第一个满足的 <code>case</code> 后跳出。与 C 和 Objective-C 不同,我们不需要使用 <code>break</code> 关键字<a href="/misc/goto?guid=4959671735322166963"><sup>1</sup></a>。</p>    <p>这意味着在上面的代码中,如果坐标是 <code>(0, 0)</code>,则它会匹配第一个 <code>case</code> 打印出 <code>"On the origin!"</code>,并就此打住,就算<code>(0, _)</code> 和 <code>(_, 0)</code> 也符合匹配的条件,它也不会再去进行匹配。因为它已经在第一个匹配之后跳出了。</p>    <h2>字符串与字符</h2>    <p>为什么要止步于元组呢?在 Swift 当中,我们也可以使用 <code>switch</code> 来对很多原生类型进行匹配,包括字符串和字符,比如:</p>    <table>     <tbody>      <tr>       <td> <pre>  <code class="language-swift">let car: Character = "J"  switch car {    case "A", "E", "I", "O", "U", "Y": print("Vowel")    default: print("Consonant")  }  </code></pre> </td>      </tr>     </tbody>    </table>    <p>可以注意到,我们可以使用按逗号分隔的多个模式来进行匹配,使符合这些模式的匹配(这里是匹配所有的元音字母)都执行同一段代码。这可以避免我们写很多重复的代码。</p>    <h2>Range</h2>    <p>Range 在模式匹配中也很有用。提醒一下,<code>Range<T></code> 是一个泛型类型,它包含了 <code>T</code> 类型的 <code>start</code> 和 <code>end</code> 成员,同时<code>T</code> 必须是一个 <code>ForwardIndexType</code>。这包括 <code>Int</code> 和 <code>Character</code> 在内的许多类型。</p>    <p>我们可以使用 <code>Range(start: 1900, end: 2000)</code> 来显式地声明一个 range,也可以使用语法糖操作符 <code>..<</code>(不包含最后一个数 <code>end</code>)或 <code>...</code>(包含最后一个数 <code>end</code>),所以我们也可以将上面的 range 写为 <code>1900..<2000</code>(更方便也更易读)</p>    <p>那么我们如何在 <code>switch</code> 当中使用它们呢?其实相当简单,在 <code>case</code> 模式中使用 range 来判断值是否落于这个范围内!</p>    <table>     <tbody>      <tr>       <td> <pre>  <code class="language-swift">let count = 7  switch count {    case Int.min..<0: print("Negative count, really?")    case 0: print("Nothing")    case 1: print("One")    case 2..<5: print("A few")    case 5..<10: print("Some")    default: print("Many")  }  </code></pre> </td>      </tr>     </tbody>    </table>    <p>可以看到我们在 <code>case</code> 当中混用了 <code>Int</code> 整型值与 <code>Range<Int></code> 的值。这样的使用并没有任何问题,只要我们保证覆盖了所有可能的情况。</p>    <p>虽说 <code>Int</code> 是最常用的 range 类型,我们也可以使用其它的 <code>ForwardIndexType</code> 类型,包括… <code>Character</code>!还记得上面写的代码么?它有一点问题,那就是对于标点符号以及其它不是 <code>A-Z</code> 的字符,它也会打印出 “Consonant”。让我们来解决这个问题<a href="/misc/goto?guid=4959671735400930122"><sup>2</sup></a>(同时也增加了小写字母):</p>    <table>     <tbody>      <tr>       <td> <pre>  <code class="language-swift">func charType(car: Character) -> String {    switch car {      case "A", "E", "I", "O", "U", "Y", "a", "e", "i", "o", "u", "y":        return "Vowel"      case "A"..."Z", "a"..."z":        return "Consonant"      default:        return "Other"    }  }  print("Jules Verne".characters.map(charType))  // ["Consonant", "Vowel", "Consonant", "Vowel", "Consonant", "Other", "Consonant", "Vowel", "Consonant", "Consonant", "Vowel"]  </code></pre> </td>      </tr>     </tbody>    </table>    <h2>类型</h2>    <p>至此一切顺利,但我们能不能更进一步呢?答案是当然没问题:让我们把模式匹配用在… 类型上!</p>    <p>在这里,我们定义了三个结构体,并遵守相同的协议:</p>    <table>     <tbody>      <tr>       <td> <pre>  <code class="language-swift">protocol Medium {    var title: String { get }  }  struct Book: Medium {    let title: String    let author: String    let year: Int  }  struct Movie: Medium {    let title: String    let director: String    let year: Int  }  struct WebSite: Medium {    let url: NSURL    let title: String  }    // And an array of Media to switch onto  let media: [Medium] = [    Book(title: "20,000 leagues under the sea", author: "Jules Vernes", year: 1870),    Movie(title: "20,000 leagues under the sea", director: "Richard Fleischer", year: 1955)  ]  </code></pre> </td>      </tr>     </tbody>    </table>    <p>然后我们要如何对 <code>Medium</code> 使用 <code>switch</code> 的模式匹配,让它对 <code>Book</code> 和 <code>Movie</code> 做不同的事呢?简单,在模式匹配中使用<code>as</code> 和 <code>is</code>!</p>    <table>     <tbody>      <tr>       <td> <pre>  <code class="language-swift">for medium in media {    // The title part of the protocol, so no need for a switch there    print(medium.title)    // But for the other properties, it depends on the type    switch medium {    case let b as Book:      print("Book published in \(b.year)")    case let m as Movie:      print("Movie released in \(m.year)")    case is WebSite:      print("A WebSite with no date")    default:      print("No year info for \(medium)")    }  }  </code></pre> </td>      </tr>     </tbody>    </table>    <p>注意到对 <code>Book</code> 和 <code>Movie</code> 使用的 <code>as</code>,我们需要确定它们是不是特定的类型,如果是,则将它们转换后的类型赋值给一个常量(<code>let b</code> 或 <code>let m</code>),因为我们之后要使用到这个常量<a href="/misc/goto?guid=4959671735490862510"><sup>3</sup></a>。</p>    <p>而另一方面,对 <code>WebSite</code> 我们只使用了 <code>is</code>,因为我们只需要检查 <code>medium</code> 是不是一个 <code>Website</code> 类型,如果是,我们并没有对它进行转换与存储在常量中(我们不需要在 <code>print</code> 语句中使用到它)。这与使用 <code>case let _as Website</code> 有点类似,因为我们只关心它是不是 <code>Website</code> 类型,而不需要它的对象的值。</p>    <blockquote>     <p>注意:如果必须在 <code>swtich</code> 匹配中使用到 <code>as</code> 和 <code>is</code>,这里有可能存在<a href="/misc/goto?guid=4959671735558769477" rel="external">代码异味</a>,比如,在上面这个特定的例子中,在<code>protocol Medium</code> 当中添加一个 <code>releaseInfo: String { get }</code> 属性就比使用 <code>switch</code> 来对不同的类型进行匹配要好。</p>    </blockquote>    <h2>下一步</h2>    <p>在接下来的部分,我们会学习如何创建可以直接使用于模式匹配的自定义类型,探索更多的语法糖,并看到如何在 <code>switch</code>语句之外使用模式匹配,以及更加复杂的匹配表达式… 迫不及待了吧!</p>    <ol>     <li>可以使用 <code>fallthrough</code> 关键字来让求值判断流向下一个 <code>case</code>。但是在实践上要使用到这个关键字的场景很少,并不经常会碰到。</li>     <li>当然,这种字符串的分析方法并不是最好的,也不是值得推荐的 —— 因为 Unicode 字符以及本地化都比这复杂得多。所以类似这样的功能我们更应该使用 <code>NSCharacterSet</code>,考虑当前的 <code>NSLocale</code> 把哪些字母定义为元音(“y” 是元音吗?还有 “õ” or “ø” 呢?),等等。不要把这个例子看得太认真,我只是用它来展示 <code>switch</code> + <code>Range</code> 的强大而已。</li>     <li>尽管与 <code>if let b = medium as? Book</code> 表达式很相似 —— 当 <code>medium</code> 可以被转换为特定类型的时候,它们都将其绑定到一个变量上 —— 但是在模式匹配中我们要使用 <code>as</code> 而非 <code>as?</code>。尽管它们的机制很相似,但是它们的语义是不同的(“尝试进行类型转换,如果失败就返回 <code>nil</code>” vs “判断这个模式是不是匹配这种类型”)。</li>    </ol>    <p>来源:http://swift.gg/2016/04/27/pattern-matching-2/ </p>