unwrapping multiple optionals in if statement

前端 未结 8 597
鱼传尺愫
鱼传尺愫 2020-11-28 07:38

I want to unwrap two optionals in one if statement, but the compiler complaints about an expected expression after operator at the password constant. What could be the reaso

8条回答
  •  一生所求
    2020-11-28 07:57

    Before Swift 1.2

    Like @James, I've also created an unwrap function, but this one uses the existing if let for control flow, instead of using a closure:

    func unwrap(optional1: T1?, optional2: T2?) -> (T1, T2)? {
      switch (optional1, optional2) {
      case let (.Some(value1), .Some(value2)):
        return (value1, value2)
      default:
        return nil
      }
    }
    

    This can be used like so:

    if let (email, password) = unwrap(self.emailField?.text, self.passwordField?.text)
    {
      // do something
    }
    

    From: https://gist.github.com/tomlokhorst/f9a826bf24d16cb5f6a3

    Note that if you want to handle more cases (like when one of the two fields is nil), you're better off with a switch statement.

提交回复
热议问题