8

I have this code

import UIKit enum menuSituation{ case menuIsOpened case menuIsClosed } class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() var currentSituation = menuSituation.menuIsClosed switch(currentSituation){ //Here is the warning case .menuIsOpened: println("Menu is opened") break case .menuIsClosed: println("Menu is closed") break } } 

In the line where I start to define switch statement, it gives me the warning :

Switch condition evaluates to a constant

How can I get rid of this warning?

0

4 Answers 4

15

Well, it basically means that the switch will always evaluate to menuIsClosed. You probably meant something like this:

var currentSituation = aSituation // That would be a menuSituation (known at runtime) // Also note that 'break' is not needed in (non-empty) match cases switch currentSituation { case .menuIsOpened: print("Menu is opened") case .menuIsClosed: print("Menu is closed") } 
Sign up to request clarification or add additional context in comments.

1 Comment

I defined a function to return me a menuSituation type and then assigned it to currentSituation, so viewDidLoad became not aware of what the actual situation of the currentSituation variable is.And the warning is gone.Thank you.
4

I had the same problem, the solution was to make the declaration globally:

import UIKit enum menuSituation{ case menuIsOpened case menuIsClosed } private var currentSituation: menuSituation = .menuIsClosed // globally declaration class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() switch currentSituation { case .menuIsOpened: println("Menu is opened") break case .menuIsClosed: println("Menu is closed") break } } } 

1 Comment

The complete example makes it understand quick. thank you.
0

Very often it helps to put a constant value into brackets. The compiler still knows it is a known value, but assumes for warnings etc. that it isn't. So just

var currentSituation = (menuSituation.menuIsClosed) 

I assume this is during development, and you will add other cases, otherwise the warning is of course fully justified and you can much simplify the code.

Comments

-2

Probably you can try in this way

 enum CompassPoint : String { case North case South case East case West } let directionToHead = "West" switch directionToHead { case "North": print("Lots of planets have a north") case "South": print("Watch out for penguins") case "East": print("Where the sun rises") case "West": print("Where the skies are blue") default : print("No direction is found") } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.