Selecting global or object print function
I am working with on a Cocoa project in Swift and confronted the following problem:
Several classes in the Cocoa Framework (such as NSWindow
or NSView
) implements a function called print:
that opens a window in order to print something (don't really know what), so when I work within a class inherited from one of these classes, and want to log something to the console for debug purposes, I use the print:
function. But the compiler thinks that I am referring to self.print:
although I am referring to the global print function.
I found a workaround by declaring a global function like so:
func myPrint(o : Any?)
{
print(o)
}
and use myPrint:
instead of print:
in cases where the compiler will confuse which function I am referring to. I am pretty sure that there probably are other functions in this case other then print:
. Is my workaround or overriding the inherited print:
function the only solution or can I give the compiler somehow a hint saying that I want to refer to the global print:
function?
PS: I am using Swift 2.0 so println:
is not available.
Indeed, NSView
has a
func print(_ sender: AnyObject?)
method to open the Print panel, which is an unfortunate conincidence.
Your myPrint()
wrapper has some limitations, for example
myPrint("b", appendNewline : false)
does not compile. A better implementation would be
func myPrint<T>(o : T, appendNewline nl: Bool = true) {
print(o, appendNewline: nl)
}
But you can simply prepend the module name "Swift" to refer to the global function explicitly:
Swift.print("xxx")
If your goal is simply to write output to the console, I would use the alternate global function debugPrint(_:)
for that purpose here.