Lesser Than or Greater Than in Swift Switch Statement

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

































































































TestChromeFirefoxOperaEdgeBraveNode
1.0 time15 ms14 ms17 ms17 ms16 ms14 ms
if-immediate1.001.001.001.001.001.00
if-indirect2.201.212.062.182.191.93
switch-immediate2.071.431.711.712.191.93
switch-range3.602.002.472.652.882.86
switch-range22.071.361.821.711.941.79
switch-indirect-array2.931.572.532.472.752.50
array-linear-switch2.733.292.122.122.382.50
array-binary-switch5.806.075.245.245.445.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



Leave a reply



Submit