【问题标题】:objective c using NSString in switch cases在切换案例中使用 NSString 的目标 c
【发布时间】:2013-09-10 11:02:45
【问题描述】:

我想将字符串作为 switch case 参数传递。怎么办??

我试过像枚举这样的

typedef enum _KeyPath
{
     KeyPathNone,
     KeyPathRefreshCount,
     KeyPathTimesLaunched,
     KeyPathCount
} KeyPath;

但我不明白如何将这个枚举值传递给 switch case。

【问题讨论】:

  • 您到底想达到什么目的? C/Objective-C 的 switch/case 语句不能用于字符串,只能用于整数值。
  • 我知道,但我想问一下,有没有什么方法可以在我的应用程序中使用枚举或任何东西,因为我需要检查许多字符串情况,为此我使用了 if else 的数量陈述。我想摆脱它。
  • @pallavi 请粘贴实际代码,也许我们可以提供帮助。将if-else 替换为switch 实际上并没有改变代码结构,这将是一个纯粹的装饰性改变。如果您想摆脱许多 if-else 语句,则必须添加更多信息。还可以考虑使用 codereview.stackexchange.com。

标签: objective-c string switch-statement case


【解决方案1】:

你使用

typedef enum _KeyPath
{
    KeyPathNone = 0,
    KeyPathRefreshCount,
    KeyPathTimesLaunched,
    KeyPathCount
} KeyPath;

现在 KeyPathNone 为 0,KeyPathRefreshCount 为 1,KeyPathTimesLaunched 为 2,……

因此您可以将实际名称作为参数传递给 switch 语句。

【讨论】:

    【解决方案2】:
    <Name of enum> <enum object> = "String value you want to pass"
    

    例子:

    enum Test{
    A,
    B
    }
    
    
    Test city = A;
    
    switch (city) {
        case B:
            //print B
        break;
    
       case A:
           //print A
           break;   
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-20
      • 1970-01-01
      相关资源
      最近更新 更多