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.
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?
// 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 .
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
. It's up to you, how you are comfortable with you code, how to explicit or not cases.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.