【问题标题】:complementery of an if caseif case 的补充
【发布时间】:2016-06-20 15:39:27
【问题描述】:

你会怎么写:

if case .SomeEnum(3) = enumType where myInt == 3 {
   //I don't need this case
} else {
   //This is the case I need
}

我知道我可以使用guard

guard case .SomeEnum(3) = enumType where myInt == 3 else {
    //This is the case I need
}

但我不认为它是干净的,因为这并不是函数无法完成的情况。另外,guard 期望我从函数中返回。

还有其他选择吗?

【问题讨论】:

  • 不就是if .SomeEnum != enumType || myInt != 3吗?
  • .SomeEnum != enumType.SomeEnum == enumType 给出编译器错误,因为枚举有参数
  • 哦,我明白了。好问题:)
  • 据我所知,您不能否定一个模式。我认为您的第一个解决方案是最好的解决方案,或者一个带有一个 case 加上 default case 的 switch 语句。 – 你可以在本地范围内使用守卫,但这更像是混淆 Swift。

标签: ios swift if-case


【解决方案1】:

你不能否定一个模式(据我所知),你的第一个解决方案 使用if/else 对我来说看起来不错,代码的意图很明显 可见。

switch 语句是一种替代方法:

switch enumType {
case .SomeEnum(3) where myInt == 3:
    break  // I don't need this case
default:
    // This is the case I need
    // ...
}

关于你的评论

另外,守卫希望我从函数中返回。

这并不完全正确。您应该离开当前范围。 所以这将按预期编译和工作:

repeat {
    guard case .SomeEnum(3) = enumType where myInt == 3 else {
        // This is the case I need
        // ...
        break
    }
} while false

但我认为这不是更好的解决方案。

【讨论】:

  • 我使用switch 也有同样的想法,不需要 模式是case .SomeEnum(let value) where value == 3 && value == myInt: 或者甚至可能只是case .SomeEnum(let value) where value == myInt:
  • @vadian: case .SomeEnum(3) where myInt == 3: 与问题中的模式相同。
  • @vadian: case .SomeEnum(let value) where value == myInt:(如果这就是 OP 的实际意思)可以缩短为 case .SomeEnum(myInt):
  • 你可以用do { ... }代替repeat { ... } while false
  • @NobodyNada:是的,但是——除非我忽略了某些东西——只有给它一个标签,你才能摆脱它:LABEL: do { ... }break LABEL
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-04
  • 1970-01-01
相关资源
最近更新 更多