Can Swift switch statements have another switch in a case?
Of course it's possible
enum Alphabet {
case Alpha, Beta, Gamma
}
enum Disney {
case Goofy, Donald, Mickey
}
let foo : Alphabet = .Beta
let bar : Disney = .Mickey
switch foo {
case .Alpha, .Gamma: break
case .Beta:
switch bar {
case .Goofy, .Donald: break
case .Mickey: print("Mickey")
}
}
Swift range check in switch
It is not possible to create a range in Swift that is open on the low end.
This will accomplish what you intended:
switch value {
case 0...f1:
print("one")
case f1...(f1 + f2):
print("two")
case (f1 + f2)...1:
print("three")
default:
print("four")
}
Since switch
matches the first case
it finds, you don't have to worry about being non-inclusive on the low end. f1
will get matched by the "one"
case, so it doesn't matter that the "two"
case also includes it.
If you wanted to make the first case exclude 0
, you could write it like this:
case let x where 0...f1 ~= x && x != 0:
or
case let x where x > 0 && x <= f1:
C++ Usage of switch statement
Question 1: Depends on the compiler. C++ standard does not require that a jump table be set up.
In many cases, especially with small number of sparse cases, GCC, MSVC and other compilers will do clause-by-clause check (as if it were an if statement). To give an example, suppose your cases were 1, 15, and 1000000. It would not be efficient code-wise to do a direct jump.
gcc has the option -fno-jump-tables
to force it to build the equivalent if-else list.
Question 2: The break statement is not required for the last clause. It should be omitted if execution should flow down.
switch-case statement without break
The break
acts like a goto
command. Or, as a better example, it is like when using return
in a void
function. Since it is at the end, it makes no difference whether it is there or not. Although, I do like to include it.
Related Topics
How to Create a Packed Data Structure in Swift
Enable + Disable Auto-Layout Constraints
Nested Types Inside a Protocol
Building User Database Model in Firebase
"Nsurl" Is Not Implicitly Convertible to "Url"; Did You Mean to Use "As" to Explicitly Convert
Is Swift Inout Parameter a Variable or a Pointer
How to Get Class Name of Parent Viewcontroller in Swift
How to Draw a Scnnode Always in Front of Others
How to Use Environment Map in Arkit
How to Remove Multiple Items from a Swift Array
How to Alloc/Dealloc Unsafe Pointers in Swift
Seeking an "Exit" Equivalent in Swift
Duplicating a Particle Emitter Effect in Sprite Kit
How to Override Layerclass in Swift
Swiftui: How to Iterate Over an Array of Bindable Objects
List All Available Audio Devices