Chapter 20: Pattern Matching

最基本的pattern matching就是switch去mapping不同的case, 這章要學習更進階的mapping方法。

大綱

If and guard

  • If 和 guard可以搭配case進行混搭

Switch

  • 利用switch可以搭多個pattern matching

  • switch使用會比if else來得更安全,因為switch會幫忙檢查所有case。

That’s why you place the midRange condition second. Even though the midRange condition would match a closeRange value, it won’t be evaluated unless the previous condition fails

  • Switch case, 優先case放在上面優先處理。

for

  • Pattern match可以用來filter array。

Wildcard pattern

Value-binding pattern

Identifier pattern

  • the identifier pattern is a sub-pattern of the value-binding pattern

Tuple pattern

  • Tuple pattern, (something, 0, 0) = (identifier, expression, expression).

  • Tuple pattern combines many patterns into one and helps you write terse code

Enumeration case pattern

  • associated value: 在這裡是指legs

  • 只有當要使用時(print), 此時會透過value-binding把值給取出來。

Optional pattern

  • 用來處理當enumeration case patterns 包含nil的狀況。

”Is” type-casting pattern

”As” type-casting pattern

  • 只有當compiler找到一個object可以轉型成string, 然後compiler會將值binding到text中。

”Qualifying with where

  • 可以利用“where”進行更近一步的filter。

Chaining with commas

  • 可以將多個if簡化成單個if完成。

Custom tuple

  • 利用custom tuple進行case轉換

Validate that an optional exists

  • 檢查optional狀態

Organize an if-else-if

  • 利用switch搭配pattern matching來替代if-else-if,可以讓code更加清楚。

Expression pattern

  • “The expression pattern compares values with the ~= pattern matching operator”

Overloading ~=

Key points

  • A pattern represents the structure of a value.

  • Pattern matching can help you write more readable code than the alternative logical conditions.

  • Pattern matching is the only way to extract associated values from enumeration values.

Last updated