Abhishek Bedi Abhishek Bedi - 2 months ago 8
Swift Question

Make Xcode (swift )throw error for print()

I created a custom Logger for logging values for different modes like debug, release but I want that whenever I use the default

print()
Xcode should throw an error explaining the user to use the custom logger.

I referred this but want to throw error there and then rather than adding a build-phase.

Any Ideas ?

Answer

You could shadow the built-in print in your module and mark it "unavailable":

// swift 3:
@available(*, unavailable, message: "use Logger instead!")
internal func print(_ items: Any..., separator: String = " ", terminator: String = "\n") {
    Swift.print(items, separator: separator, terminator: terminator)
}

// swift 2:
@available(*, unavailable, message="use Logger instead!")
internal func print(items: Any..., separator: String = " ", terminator: String = "\n") {
    Swift.print(items, separator: separator, terminator: terminator)
}

The result looks like:

Xcode errors

(There is still another instance of print<Target>(..., to output: inout Target) which I don't bother to hide, I guess no one will accidentally use that function.)

As shown, you could still use the qualified name Swift.print to refer to the real function in case of emergency.

Note that this will only affect your own module. You can't force users outside of your module to not use print.

Comments