1
2
3
4
let limit = array.count
if 0...limit ~= limit {
// to do something
}

> Wildcard Pattern

1
2
3
for _ in 1...3 {
// Do something three times.
}

> Identifier Pattern

1
let someValue = 42

> Value-Binding Pattern

1
2
3
4
5
6
7
let point = (3, 2)
switch point {
// Bind x and y to the elements of point.
case let (x, y):
print("The point is at (\(x), \(y)).")
}
// Prints "The point is at (3, 2)."

> Tuple Pattern

1
2
3
4
5
let points = [(0, 0), (1, 0), (1, 1), (2, 0), (2, 1)]
// This code isn't valid.
for (x, 0) in points {
/* ... */
}

INCREDIBLE!!!😍

> Optional Pattern

1
2
3
4
5
6
7
8
9
10
let someOptional: Int? = 42
// Match using an enumeration case pattern.
if case .some(let x) = someOptional {
print(x)
}
// Match using an optional pattern.
if case let x? = someOptional {
print(x)
}

The optional pattern provides a convenient way to iterate over an array of optional values in a for-in statement, executing the body of the loop only for non-nil elements.

1
2
3
4
5
6
7
8
et arrayOfOptionalInts: [Int?] = [nil, 2, 3, nil, 5]
// Match only non-nil values.
for case let number? in arrayOfOptionalInts {
print("Found a \(number)")
}
// Found a 2
// Found a 3
// Found a 5

> Expression Pattern

1
2
3
4
5
6
7
8
9
10
let point = (1, 2)
switch point {
case (0, 0):
print("(0, 0) is at the origin.")
case (-2...2, -2...2):
print("(\(point.0), \(point.1)) is near the origin.")
default:
print("The point is at (\(point.0), \(point.1)).")
}
// Prints "(1, 2) is near the origin."

can improve by overload the tilde operator ~=.

1
2
3
4
5
6
7
8
9
10
11
// Overload the ~= operator to match a string with an integer.
func ~=(pattern: String, value: Int) -> Bool {
return pattern == "\(value)"
}
switch point {
case ("0", "0"):
print("(0, 0) is at the origin.")
default:
print("The point is at (\(point.0), \(point.1)).")
}
// Prints "The point is at (1, 2)."