加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – 你能装饰一个破坏调试的函数来代替调用该函数的位置吗

发布时间:2020-12-14 04:32:23 所属栏目:百科 来源:网络整理
导读:最好用一个例子来解释.考虑一下这个mustOverride辅助函数: func mustOverride(callSite:String = #function) - Never { preconditionFailure("(callSite) must be overridden in a subclass")} 我们使用它来制作虚假抽象类,如下所示: // Faux 'abstract'
最好用一个例子来解释.考虑一下这个mustOverride辅助函数:

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以下划线开头,因此将来可能会发生变化

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读