unwrapping multiple optionals in if statement

前端 未结 8 563
鱼传尺愫
鱼传尺愫 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:43

    Swift 4

    if let suggestions = suggestions, let suggestions1 = suggestions1 {
    
            XCTAssert((suggestions.count > suggestions1.count), "TEST CASE FAILED: suggestion is nil. delete sucessful");
    }
    
    0 讨论(0)
  • 2020-11-28 07:48

    The usage

    if let x = y {
    }
    

    is not equivalent to

    if (let x = y) { // this is actually not allowed
    }
    

    "if let" is effectively a two-word keyword, which is equivalent to

    if y != nil {
        let x = y!
        // rest of if let block
    }
    
    0 讨论(0)
  • 2020-11-28 07:50

    How about wrapping the optionals in a tuple and using switch to pattern match?

    switch (self.emailField?.text, self.passwordField?.text) {
    case let (.Some(email), .Some(password)):
        // unwrapped 'email' and 'password' strings available here
    default:
        break
    }
    

    It's definitely a bit noisier, but at least it could also be combined with a where clause as well.

    0 讨论(0)
  • 2020-11-28 07:51

    Update for Swift 3:

    if let email = emailField?.text, let password = passwordField?.text {
    }
    

    each variable must now be preceded by a let keyword

    0 讨论(0)
  • 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<T1, T2>(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.

    0 讨论(0)
  • 2020-11-28 07:59

    I can't explain why the above code doesn't work, but this would be good a replacement:

    if let email = self.emailField?.text 
    {
        if let password = self.passwordField?.text 
        {
            //do smthg
        }
    }
    
    0 讨论(0)
提交回复
热议问题