The pattern matching operator
In Swift, the pattern matching operator (~=) is used to compare a value against a pattern. It returns true if the value matches the pattern and false otherwise.
The pattern-matching operator can be used in a variety of contexts, including switch statements, if statements, and guard statements.
Here are some examples of using the pattern-matching operator:
// Matching against a range
let x = 5
if 0...10 ~= x {
print("x is between 0 and 10")
}
In the first example, the pattern-matching operator is used to check whether the value of x is between 0 and 10 (inclusive). The range 0...10 is the pattern, and x is the value being matched against the pattern.
// Matching against a tuple
let point = (1, 2)
if case (0, _)...(_, 0) ~= point {
print("point is on or inside the x/y axis")
}
In the second example, the pattern matching operator is used to check whether the point tuple is on or inside the x/y axis. The pattern is (0, _)...(_, 0) which matches any tuple where the first value is between 0 and the second value and at least one of the values is 0.
Comments
Post a Comment