简体   繁体   English

switch 语句的 default case 是否调用了先前的 case?

[英]Have switch statement's default case call a prior case?

Whenever I use a switch-case statement – 9 times out of 10 – the final default case is almost always that of a case above it.每当我使用switch-case语句时——10 次中有 9 次——最终的default情况几乎总是在它上面的情况下。

ie. IE。

// WebView Observers
switch webView {
    case webView:
        webViewURLObserver = webView.observe(\.url, options: .new) { [weak self] webView, change in
            let url = "\(String(describing: change.newValue))"
            self?.urlDidChange(urlString: url) }
    case customizerWebView:
        customizerURLObserver = customizerWebView.observe(\.url, options: .new) { [weak self] webView, change in
            let url = "\(String(describing: change.newValue))"
            self?.customizerURLDidChange(urlString: url) }
    case default:
        webViewURLObserver = webView.observe(\.url, options: .new) { [weak self] webView, change in
        let url = "\(String(describing: change.newValue))"
        self?.urlDidChange(urlString: url) }
    }

Is there a way to have the default case just reference one of the already-existing cases?有没有办法让default案例只引用一个已经存在的案例?

// What I'm trying to accomplish
switch webView {
    case webView:
        [webView Observer Code]
        ...
    case customizerWebView:
        [customizerWebView Observer Code]
        ...
    case default:
        switch.case = webView || switch.case = 0
    }

A possible solution is to use fallthrough .一个可能的解决方案是使用fallthrough

Instead of thinking:而不是思考:

In case of "default": do something of target case在“默认”的情况下:做一些目标案例

Think it in the other way:换个角度想想:

In case of target case, do "default".如果是目标案例,请执行“默认”。

switch webView {
case customizerWebView:
    customizerURLObserver = customizerWebView.observe(\.url, options: .new) { [weak self] webView, change in
        let url = "\(String(describing: change.newValue))"
        self?.customizerURLDidChange(urlString: url) }
case webView:
        fallthrough
case default:
    webViewURLObserver = webView.observe(\.url, options: .new) { [weak self] webView, change in
    let url = "\(String(describing: change.newValue))"
    self?.urlDidChange(urlString: url) }
}

Or as, pointed by @xTwiteDx , you can remove the lines case webView: fallthrough if you don't do a specific code before fallthrough .或者,正如@xTwiteDx 所指出的,如果您在fallthrough之前没有执行特定代码,则可以删除行case webView: fallthrough fallthrough It's up to you, how you are comfortable with you code, how to explicit or not cases.这取决于您,您对代码的适应程度如何,如何明确或不明确案例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM