vendredi 14 juillet 2017

Swift 3 enum with associated value AND function comparison

I have this struct that has an enum property as well as a function:

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...
  }
}

Is there a way to rewrite the following conditionals so that the check for isConfigured() and state are in the same statement?

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

It seems because the State enum uses associated values, you cannot simply write if userInput.state == .restricted || userInput.isConfigured(), you need to use the if case syntax. There must be a way around this?

Aucun commentaire:

Enregistrer un commentaire