Switch Statement in Swift

Switch statement in Swift

The usual rules for the FizzBuzz game
are to replace every multiple of 3 by "Fizz", every multiple of 5 by "Buzz", and
every multiple of both 3 and 5 by "FizzBuzz".

This can be done with a switch statement on the tuple (i % 3, i % 5).
Note that _ means "any value":

for i in 1 ... 100 {
switch (i % 3, i % 5) {
case (0, 0):
print("FizzBuzz")
case (0, _):
print("Fizz")
case (_, 0):
print("Buzz")
default:
print(i)
}
}

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 case statement

A switch statement considers a value and compares it against several possible matching patterns. It then executes an appropriate block of code, based on the first pattern that matches successfully.

In your specific case try to use:

var grade = 45

switch grade {

case 90 ..< 100: //Numbers 90-99 Use 90...100 to 90-100
print("A")
case (80 ..< 90): //80 - 89
print("B")
case (70 ..< 80): // 70 - 79
print("C")
case (0 ..< 70): // 0 - 69
print("D")

default:
print("F. You failed")//Any number less than 0 or greater than 99

}

check this

In contrast with switch statements in C and Objective-C, switch
statements in Swift do not fall through the bottom of each case and
into the next one by default. Instead, the entire switch statement
finishes its execution as soon as the first matching switch case is
completed, without requiring an explicit break statement. This makes
the switch statement safer and easier to use than the one in C and
avoids executing more than one switch case by mistake.

Regards

Does Swift have a Switch *expression* (as opposed to a Switch *statement*) like C#?

Unfortunately, Swift does not have switch expressions, only switch statements. The Swift language grammar currently supports the following as expressions:

  • References to identifiers
  • Literals
  • Self expressions (self.<whatever>, self[<whatever>], etc.)
  • Superclass expressions (super.<whatever>, super[<whatever>], etc.)
  • Closures
  • Parenthesized expressions (expressions, in parentheses)
  • Tuples
  • Implicit member expressions (references to functions or variables that would reference self, but based on context, are allowed to skip referencing self — e.g. foo(123) as opposed to self.foo(123))
  • Wildcards (_)
  • Key paths, selectors, and key path strings

Note that things like control flow statements, do statements, and others are not included in this list — Swift only allows those as full statements. Currently, statements can be composed of:

  • Expressions
  • Declarations
  • Loop statements
  • Branch statements (if/guard/switch)
  • Labeled statements (label: <some statement>)
  • Control transfer statements (break, continue, etc.)
  • Defer statements
  • Do statements
  • Compiler control statements (#if ..., #error, #warning, etc.)

This is something currently intimately tied to the core of the language, so changing it would be no small feat! For this reason, this feature is also at the top of the list of the Swift "commonly rejected changes" list for control flow:

if/else and switch as expressions: These are conceptually interesting things to support, but many of the problems solved by making these into expressions are already solved in Swift in other ways. Making them expressions introduces significant tradeoffs, and on balance, we haven't found a design that is clearly better than what we have so far.

Despite this, this is something that comes up periodically on the forums, and has been discussed extensively (e.g. If / else expressions, which contains a lot of discussion of switch expressions too). This is something that plenty of folks want, so I'd recommend getting an understanding the latest state of things by reading through some of the threads on the forums for ideas on what/how to constructively propose, if you're interested!

Convert from switch case statement to a value in Swift

You are nearly there!

You've created a closure that returns a color, and are assigning it to a UIColor property, but a closure is not a color!

You just need to call (invoke) the closure to run it, so that it returns the color you want:

self.backgroundColor = {
switch type {
case .teuro:
return UIColor.sapphireColor()
case .lesson:
return UIColor.orangeColor()
case .profession:
return UIColor.pinkyPurpleColor()
}
}() // <---- notice the brackets!

Switch case formatting issue with SwiftLint

You can adjust that setting on Xcode with the following checkbox. I think it comes unchecked by default, which should match SwiftLint's default rules.

Xcode indentation settings

Switch Statement on didSelectRowAt Function in Swift

try my code

var count = 0
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
count += 1
let cell = tableView.cellForRow(at: indexPath)
switch count {
case 1:
cell.cellLabel.text = "first time label changes"
case 2:
cell.cellLabel.text = "second time label changes"

default:
cell.cellLabel.text = "change the label"
}
}

if you need "first" when you touch it 3 times

 var count = 0
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
count += 1
if count > 2 {
count = 1
}
let cell = tableView.cellForRow(at: indexPath)
switch count {
case 1:
cell.cellLabel.text = "first time label changes"
case 2:
cell.cellLabel.text = "second time label changes"
default:
cell.cellLabel.text = "change the label"
}
}

How to return a function from inside a switch-case statement

following @JoakimDanielson advice I changed myServerFunction to throw instead of failing a completion handler:

func myServerFunction(finishesSuccessful:Bool) throws {
if finishesSuccessful {
print("Upload to Server successful")
} else {
throw MyError.serverError
}
}

Now I can catch the error in myMainFunction

if uploadToServer {
do {
try myServerFunction(finishesSuccessful: false)
} catch {
completionHandler(.failure(.serverError))
return
}
}


Related Topics



Leave a reply



Submit