swift

How to get the compiler to prefer my function over a Swift general function?


I have this function

@inlinable
public func assert(
  _ condition: @autoclosure () -> Bool = Bool(),
  _ message: @autoclosure () -> String = String(),
  attributes: [String: Any]? = nil,
  file: StaticString = #file,
  line: UInt = #line
) {
  print("OURS")
  if !condition() {
    assertionFailure(message, attributes: attributes, file: file, line: line)
  }
}

and I want to be able to call assert(1==2) in my code, but the print doesn't show in the log, and it seems that the global Swift.assert function is called instead.

No matter how I change the @autoclosure (with/without it, with/without a default value), or whether it is @inlinable or not, public or not, I get the same result. I don't want to rename my function and I don't want to nest it in a class (so that it can be prefixable)


Solution

  • With function overloads, the compiler always prefers the most specialised version. If your function isn't more specialised than the built in one, but simply adds more input parameter with default input arguments, the compiler cannot distinguish it from the Swift standard library one.

    You need to use names-acing and call your function with your own module name, like

    MyModule.assert(1 == 2)