1

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)

K.R.
  • 312
  • 3
  • 16

1 Answers1

3

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)
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
  • Thanks. I was afraid of that. What would be my module name then? It is an iOS app with this function declared in one of the folders in a file named `Assertions.swift` – K.R. Jun 10 '20 at 08:37
  • The module is defined by the target, not by file names or folders. So your module name should be the name of your target. – Dávid Pásztor Jun 10 '20 at 08:50
  • My target has spaces in it, how will that work - it is "My App" – K.R. Jun 10 '20 at 08:53
  • 1
    @K.R. check [this](https://stackoverflow.com/a/36611849/4667835) answer for how to figure out your module name – Dávid Pásztor Jun 10 '20 at 08:54