[英]Is there any way to have a subclass's override method return when a guard block on the super class is invoked
Currently I have a super class: 目前我有一个超级班:
class ShareButtonAction : ButtonAction {
override func execute() {
guard let isReachable = reachability?.isReachable() where isReachable == true else {
print("No network connection")
return
}
}
And a child class of ShareButtonAction: 还有一个ShareButtonAction的子类:
class ShareTwitterAction : ShareButtonAction {
override func execute() {
super.execute()
guard let isReachable = reachability?.isReachable() where isReachable == true else {
return
}
}
I don't want the child class's implementation of execute to be fired off if the guard condition is caught in the superclass. 我不希望如果在超类中捕获了警戒条件,则将激发子类的execute实施。 Currently I have to duplicate code which is bothering me.
目前,我必须复制困扰我的代码。
Is there a way to tell the child class dont bother executing if the superclass guard is caught. 有没有一种方法可以告诉子类不要被超类后卫抓住而烦恼执行。
I know I can fall back to passing blocks and not execute the containing block of the guard fails although I feel like there should be a built in mechanism in swift to make this easier. 我知道我可以退回到传递的块中,并且不执行保护失败的包含块,尽管我觉得应该有一个内置的机制来使之更容易。 I am hoping I just have not found it yet.
我希望我还没有找到它。
The built-in mechanisms are either returning a value from the superclass implementation, or throwing an exception there. 内置机制要么从超类实现中返回一个值,要么在那里抛出异常。 In a simple case, have the method return a boolean value.
在简单的情况下,让该方法返回布尔值。 The subclass implementation can check the return value from the superclass call.
子类实现可以检查超类调用的返回值。
You could make the method return a boolean value and use that to decide if you want to execute the code in the subclass. 您可以使该方法返回一个布尔值,然后使用该值确定是否要执行子类中的代码。
class ShareButtonAction : ButtonAction {
override func execute() -> Bool {
guard let isReachable = reachability?.isReachable() where isReachable else {
print("No network connection")
return false
}
return true
}
}
class ShareTwitterAction : ShareButtonAction {
override func execute() -> Bool {
let result = super.execute()
if result {
//... your code here
}
return result
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.