Lesser than or greater than in Swift switch statement
Here's one approach. Assuming someVar
is an Int
or other Comparable
, you can optionally assign the operand to a new variable. This lets you scope it however you want using the where
keyword:
var someVar = 3
switch someVar {
case let x where x < 0:
print("x is \(x)")
case let x where x == 0:
print("x is \(x)")
case let x where x > 0:
print("x is \(x)")
default:
print("this is impossible")
}
This can be simplified a bit:
switch someVar {
case _ where someVar < 0:
print("someVar is \(someVar)")
case 0:
print("someVar is 0")
case _ where someVar > 0:
print("someVar is \(someVar)")
default:
print("this is impossible")
}
You can also avoid the where
keyword entirely with range matching:
switch someVar {
case Int.min..<0:
print("someVar is \(someVar)")
case 0:
print("someVar is 0")
default:
print("someVar is \(someVar)")
}
Switch statement for greater-than/less-than
When I looked at the solutions in the other answers I saw some things that I know are bad for performance. I was going to put them in a comment but I thought it was better to benchmark it and share the results. You can test it yourself. Below are my results (ymmv) normalized after the fastest operation in each browser.
Here is the results from 2021-MAY-05
Test | Chrome | Firefox | Opera | Edge | Brave | Node |
---|---|---|---|---|---|---|
1.0 time | 15 ms | 14 ms | 17 ms | 17 ms | 16 ms | 14 ms |
if-immediate | 1.00 | 1.00 | 1.00 | 1.00 | 1.00 | 1.00 |
if-indirect | 2.20 | 1.21 | 2.06 | 2.18 | 2.19 | 1.93 |
switch-immediate | 2.07 | 1.43 | 1.71 | 1.71 | 2.19 | 1.93 |
switch-range | 3.60 | 2.00 | 2.47 | 2.65 | 2.88 | 2.86 |
switch-range2 | 2.07 | 1.36 | 1.82 | 1.71 | 1.94 | 1.79 |
switch-indirect-array | 2.93 | 1.57 | 2.53 | 2.47 | 2.75 | 2.50 |
array-linear-switch | 2.73 | 3.29 | 2.12 | 2.12 | 2.38 | 2.50 |
array-binary-switch | 5.80 | 6.07 | 5.24 | 5.24 | 5.44 | 5.37 |
Switch case with range
This should work.
private func calculateUserScore() -> Int {
let diff = abs(randomNumber - Int(bullsEyeSlider.value))
switch diff {
case 0:
return PointsAward.bullseye.rawValue
case 1..<10:
return PointsAward.almostBullseye.rawValue
case 10..<30:
return PointsAward.close.rawValue
default:
return 0
}
}
It's there in the The Swift Programming Language book under Control Flow -> Interval Matching.
Swift Switch statement fails to match strings: What could cause this?
I suspect the problem is actually in your getWatchModel
method, specifically in the line:
var machine = CChar()
This allocates a single byte. You need to allocate size
bytes.
Here's one way of doing it:
func getWatchModel() -> String? {
var size: size_t = 0
sysctlbyname("hw.machine", nil, &size, nil, 0)
var machine = [CChar](repeating: 0, count: size)
sysctlbyname("hw.machine", &machine, &size, nil, 0)
return String(cString: machine, encoding: .utf8)
}
I suspect this lead to the String
containing garbage. I'm actually surprised you did not see any crashes.
Swift: Using a comparative operator in a Switch Statement
Is a simple solution, bind it to a constant like this:
var score = 101
var letterGrade = ""
switch score{
case let x where x > 100:
letterGrade = "A+ With Extra Credit"
case 90...100:
letterGrade = "A"
case 80...89:
letterGrade = "B"
case 70...79:
letterGrade = "C"
case 60...69:
letterGrade = "D"
default:
letterGrade = "Incomplete"
}
That works exactly as you need
Javascript switch greater than / less than operators not working
Why are the greater than / less than operators not working?
Because you are comparing a number (ScreenWidth
) against a boolean (ScreenWidth > 799
). switch
compares the values using strict comparison for equality testing, so comparing different data types will always result in false
.
Changing the first case to
case (ScreenWidth = 800):
does indeed work.
That's because =
is an assignment and the result of ScreenWidth = 800
is 800
, so you are comparing against a number, which is fine.
I have also tried using "switch (TRUE)" which does absolutely nothing at all, not even the default case.
Well, TRUE
does not exist in JavaScript. JS is case-sensitive. switch(true)
should work fine.
Swift switch statement not covering all cases
As you've discovered, your cases don't cover all of the numerical possibilities. Also, your color
should likely be a computed property based on the current state of the Binding
, rather than something you set in init
:
struct ProgressBar: View {
@Binding var progress: Double
var color: Color {
switch progress {
case 0.0..<0.20:
return .blue
case 0.20..<0.40:
return .green
case 0.40..<0.60:
return .yellow
case 0.60...1.0:
return .red
default:
return .black
}
}
var body: some View {
color
}
}
AsyncImage. Cannot use switch statement in Phase closure?
you can use a switch statement, use this, works for me:
case .failure(_): // <-- here
Here is the code I used to show that my answer works:
struct ContentView: View {
@State private var stringURL = "https://upload.wikimedia.org/wikipedia/commons/e/ef/Red-billed_gull%2C_Red_Zone%2C_Christchurch%2C_New_Zealand.jpg"
var body: some View {
AsyncImage(url: URL(string: stringURL)) { phase in
switch phase {
case .empty:
ProgressView()
case .success(let image):
image.resizable().scaledToFit()
case .failure(_): // <-- here
EmptyView()
@unknown default:
Image(systemName: "exclamationmark.icloud")
}
}
}
}
Related Topics
Make Code With Firebase Asynchronous
How to Check Two Instances Are the Same Class/Type in Swift
Cllocationcoordinate2D Can't Be Instantiated
How to Scale Text to Fit Parent View with Swiftui
Swift: Property Conforming to a Specific Class and in the Same Time to Multiple Protocols
How to Get Rgb Components from Color in Swiftui
Can't Programmatically Change Color Set in Storyboard as Color from Xcassets Catalog
Iboutlet of Another View Controller Is Nil
Swift Firebase Must Be a Non-Empty String and Not Contain '.' '#' '$' '[' or ']'
Swift Sphere Combine Star Data
Spritekit Physics in Swift - Ball Slides Against Wall Instead of Reflecting
Previewprovider and Observedobject Properties
Swift 2 to 3 Migration for Prepareforsegue
What's the Difference Between Struct Based and Class Based Singletons
Simple Way to Read Local File Using Swift
Swift Nspredicate Throwing Exc_Bad_Access(Code=1, Address=0X1) When Compounding Statements
How to Use a @Fetchrequest with the New Searchable Modifier in Swiftui