Example of creating a custom operator with protocol and method under Swift 4:

  • declare the RegularExpressionMatchable protocol, with a single match method
  • extend String to conform to the newly declared protocol
  • implement the generic ~= operator, which conform to the RegularExpressionMatchableProtocol
  • the user can either use the match method or the operator to perform regex matching on String
protocol RegularExpressionMatchable {
    func match(pattern: String, options: NSRegularExpression.Options) -> Bool
}

extension String: RegularExpressionMatchable {
    func match(pattern: String, options: NSRegularExpression.Options = []) -> Bool {
        let regex = try? NSRegularExpression(pattern: pattern, options: options)
        
        if let regex = regex {
            return regex.numberOfMatches(in: self, options: [], range: NSMakeRange(0, self.utf16.count)) != 0
        }
        
        return false
    }
}

precedencegroup RegularExpressionMatchablePrecedence {
    associativity: right
    higherThan: MultiplicationPrecedence
}

infix operator ~=: RegularExpressionMatchablePrecedence

func ~=<T: RegularExpressionMatchable> (left: T, right: String) -> Bool {
    return left.match(pattern: right, options: [])
}

let foo = "Foo"
print(foo.match(pattern: "foo", options: NSRegularExpression.Options.caseInsensitive))
print(foo.match(pattern: "bar", options: NSRegularExpression.Options.caseInsensitive))