switch 语句的默认情况是否调用了先前的情况?

Have switch statement's default case call a prior case?

每当我使用 switch-case 语句时——10 次中有 9 次——最终的 default 情况几乎总是在它上面的情况。

// 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) }
    }

有没有办法让 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
    }

一个可能的解决方案是使用 fallthrough.

而不是思考:

In case of "default": do something of target case

换一种方式思考:

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) }
}

或者如 所指,如果您在 fallthrough 之前不执行特定代码,则可以删除行 case webView: fallthrough。这取决于你,你对你的代码的适应程度,如何显式或不显式。