问题描述
我正在使用Swift中的Cocoa项目,并遇到以下问题:
Cocoa框架中的几个类(例如 NSWindow
或 NSView
)实现一个名为 print:
的函数,打开一个窗口以打印一些东西(真的不知道什么),所以当我在一个继承自这些类之一的类中工作,并且希望将一些东西记录到控制台进行调试时,我使用 print:
函数。但是编译器认为我指的是 self.print:
,尽管我是指全局打印函数。
我发现了一个解决方法,通过声明一个全局函数像这样:
func myPrint(o:Any?)
{
print(o)
}
并使用 myPrint:
而不是 print:
在编译器会混淆我指的是哪个函数的情况下。我相当肯定,在这种情况下可能有其他函数,然后 print:
。是我的解决方法还是重写继承的 print:
函数的唯一解决方案,或者我可以给编译器一个提示说,我想引用全局 print:
function?
PS:我使用的是Swift 2.0,因此 println:
func print(_ sender:AnyObject?)
$ b $
您的 myPrint()
wrapper有一些限制,例如
myPrint(b,appendNewline:false)
不编译。更好的实现是
func myPrint< T>(o:T,appendNewline nl:Bool = true){
print(o,appendNewline:nl)
}
>你可以简单地添加模块名称Swift来显式地引用全局函数:
Swift.print )
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")
这篇关于选择全局或对象打印功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!