![](/img/trans.png)
[英]Switch in Swift - Case label in a switch should have at least one executable statement
[英]Have switch statement's default case call a prior case?
每當我使用switch-case
語句時——10 次中有 9 次——最終的default
情況幾乎總是在它上面的情況下。
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) }
}
有沒有辦法讓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 。
而不是思考:
在“默認”的情況下:做一些目標案例
換個角度想想:
如果是目標案例,請執行“默認”。
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) }
}
或者,正如@xTwiteDx 所指出的,如果您在fallthrough
之前沒有執行特定代碼,則可以刪除行case webView: fallthrough
fallthrough 。 這取決於您,您對代碼的適應程度如何,如何明確或不明確案例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.