最好用一个例子来解释.考虑一下这个mustOverride辅助函数: func mustOverride(callSite:String = #function) - Never { preconditionFailure("\(callSite) must be overridden in a subclass")} 我们使用它来制作虚假抽象类
func mustOverride(callSite:String = #function) -> Never { preconditionFailure("\(callSite) must be overridden in a subclass") }
我们使用它来制作虚假抽象类,如下所示:
// Faux 'abstract' class class SoundBase { func play(){ mustOverride() } } // 'Concrete' class class CatSound : SoundBase { override func play(){ // play cat 'meow' sound } }
如上所述,如果直接实例化SoundBase并调用play(),则会触发mustOverride()函数,该函数在可调试状态下中断.问题是它在mustOverride()函数内断开,而不是在调用站点play().
Microsoft的.NET有一个简洁的功能,您可以使用属性来修饰函数,以更改它们与调试器的交互方式(see here了解更多信息).
例如,它们有一个DebuggerHidden属性,如果应用于mustOverride(),会导致调试器在调用play()函数内部而不是在mustOverride()内部,这样可以避免不必要的调用栈之类的操作.上一层找出错误的真正位置.
我想知道Swift是否有类似这种能力的东西.如果使用得当,它真的很棒.
假设您正在使用Xcode进行调试,那么您要查找的是@_transparent
属性.这是在行动:
@_transparent func mustOverride(callSite: String = #function) -> Never { preconditionFailure("\(callSite) must be overridden in a subclass") } class SoundBase { func play(){ mustOverride() } } class CatSound: SoundBase { override func play() {} } SoundBase().play()
结果:
从文档:
Semantically,
@_transparent
means something like “treat this operation as if it were a primitive operation”. The name is meant to imply that both the compiler and the compiled program will “see through” the operation to its implementation.
注意:
>由于@_transparent以下划线开头,因此将来可能会发生变化