Summer Summer - 6 months ago 25
Swift Question

"pattern-match" operator ~= causes "Binary operator '~=' cannot be operand" error in Swift

I was trying out Swift new operator

~=
but ran into a weird error.

var filteredNumbers1 = [20,30,50,15].filter({15...30 ~= $0})


Works as expected.

var filteredNumbers2 = [20,30,50,15].filter({$0 ~= 15...30})


Throws error


Binary operator '~=' cannot be applied to operands of type 'int' and 'Range < Int >'


I am wondering what is the difference between
15...30 ~= $0
and
$0 ~= 15...30
?

Answer

~= in the Swift standard library is defined to expect the pattern on the left and the value on the right. The declaration is:

public func ~=<I : ForwardIndexType where I : Comparable>(pattern: Range<I>, value: I) -> Bool

You could add your own version which supports value on the left and range on the right if you like with something like:

func ~=<I : ForwardIndexType where I : Comparable>(value: I, pattern: Range<I>) -> Bool {
    return pattern ~= value
}