Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
531 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...