Swift 3枚举,具有相关的值和函数比较

时间:2017-07-14 09:17:54

标签: swift if-statement swift3 syntax enums

我有这个结构,它有一个枚举属性和一个函数:

struct UserInput {
  enum State {
    case unrestricted
    case restricted(because: WarningType)

    enum WarningType {
      case offline
      case forbidden
    }
  }

  var config: UserInputConfig?
  var state: State = .unrestricted

  func isConfigured() -> Bool {
    // Arbitrary checks about the config...
  }
}

有没有办法重写以下条件,以便检查isConfigured()state是否在同一个语句中?

if case .restricted = userInput.state {
  return 1
} else if userInput.isConfigured() {
  return 1
} else {
  return 0
}

似乎因为State枚举使用关联值,您不能简单地编写if userInput.state == .restricted || userInput.isConfigured(),您需要使用if case语法。必须有办法解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

您想这样做:

if case .restricted = userInput.state || userInput.isConfigured() {
    return 1
} else {
    return 0
}

但目前无法使用模式匹配进行 OR 。有几种方法可以做 AND

使用DeMorgan's Laws,您可以将if a || b转换为if !(!a && !b),然后撤消您{的然后 else 条款{1}}语句,您只需检查if

很遗憾,您不能说if !a && !b,但由于您的枚举只有2个案例,因此可以将其替换为if !(case .restricted = userInput.state)

现在,你如何在另一个声明中使用它?出于与无法使用if case .unrestricted = userInput.state相同的原因,您无法使用&&

您可以使用匹配两个失败条件(使用 AND )的模式检查失败案例,如果两个失败条件都不满足,则返回||:< / p>

1

等效地,您可以使用多子句条件

if case (.unrestricted, false) = (userInput.state, userInput.isConfigured()) {
    return 0
} else {
    return 1
}

除了缩短和IMO更容易阅读之外,第二种方法可以短路并在if case .unrestricted = userInput.state, !userInput.isConfigured() { return 0 } else { return 1 } 失败的情况下跳过调用userInput.isConfigured

答案 1 :(得分:1)

您可以使用switch语句和模式匹配非常干净地完成:

switch userInput.state
{
   case .unrestricted:
        return userInput.isConfigured() ? 1 : 0;

   case .restricted(_):
        return 1
}