Summer Summer - 2 years ago 85
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
$0 ~= 15...30

Answer Source

~= 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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download