Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
487 views
in Technique[技术] by (71.8m points)

swift - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...