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

问题描述 投票:6回答:3

我有这个代码

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语句的行中,它给出了警告:

切换条件评估为常量

我怎么能摆脱这个警告?

ios swift switch-statement
3个回答
9
投票

好吧,它基本上意味着开关将始终评估为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
投票

我有同样的问题,解决方案是全局声明:

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
投票

也许你可以这样试试

 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")
    }
© www.soinside.com 2019 - 2024. All rights reserved.