切换条件在Swift中计算为常量

时间:2015-07-11 11:14:37

标签: ios swift switch-statement

我有这段代码

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

        }    
    }

在我开始定义switch语句的行中,它给出了警告:

  

开关条件评估为常量

我怎样摆脱这个警告?

4 个答案:

答案 0 :(得分:8)

嗯,这基本上意味着交换机将始终评估为menuIsClosed。你可能意味着这样的事情:

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:
        println("Menu is opened")
    case .menuIsClosed:
         println("Menu is closed")
} 

答案 1 :(得分:0)

我遇到了同样的问题,解决方案是在全局范围内进行声明

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

        }    
    }
}

答案 2 :(得分:0)

通常,将恒定值放在方括号中会很有帮助。编译器仍然知道它是一个已知值,但出于警告等原因假定它不是。所以

var currentSituation = (menuSituation.menuIsClosed)

我认为这是在开发过程中,您将添加其他情况,否则,警告当然是有充分根据的,您可以大大简化代码。

答案 3 :(得分:-2)

可能你可以这样试试

 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")
    }