Skip to content

Commit a59a6ca

Browse files
committed
[stdlib] Add a transparent specialization of ~= for Range
Making the generic ~= transparent does not help unoptimized code; adding a specialization does.
1 parent 7cd41df commit a59a6ca

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

stdlib/public/core/Range.swift

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,35 @@ extension RangeExpression {
9696
@inlinable
9797
public static func ~= (pattern: Self, value: Bound) -> Bool {
9898
return pattern.contains(value)
99-
}
99+
}
100+
}
101+
102+
extension Range {
103+
/// Returns a Boolean value indicating whether a value is included in a
104+
/// range.
105+
///
106+
/// You can use the pattern-matching operator (`~=`) to test whether a value
107+
/// is included in a range. The pattern-matching operator is used
108+
/// internally in `case` statements for pattern matching. The following
109+
/// example uses the `~=` operator to test whether an integer is included in
110+
/// a range of single-digit numbers:
111+
///
112+
/// let chosenNumber = 3
113+
/// if 0..<10 ~= chosenNumber {
114+
/// print("\(chosenNumber) is a single digit.")
115+
/// }
116+
/// // Prints "3 is a single digit."
117+
///
118+
/// - Parameters:
119+
/// - pattern: A range.
120+
/// - bound: A value to match against `pattern`.
121+
@_transparent
122+
public static func ~= (pattern: Self, value: Bound) -> Bool {
123+
// Note: `Range.~=` is used particularly frequently to implement bounds
124+
// checks. This more specific variant of the generic `=~` is intended to
125+
// help improve unoptimized performance of these cases.
126+
pattern.contains(value)
127+
}
100128
}
101129

102130
/// A half-open interval from a lower bound up to, but not including, an upper

0 commit comments

Comments
 (0)