0

There are two UIAlertView variables but only one is optional. Let's say

lazy var a: UIAlertView = {

    return UIAlertView() // Which is not important here
}()

var b: UIAlertView?

and the delegate method

func alertView(alertView: SPAlertView!, clickedButtonAtIndex buttonIndex: Int) {

    switch (alertView, buttonIndex) {

    case (a, 0): // Do something
    case (a, 1): // Do something 
    case (b, 1): // <== Want to do something here but, b is optional.
    default: break
    }
}

How to unwrap b while pattern matching?

NB: The questions is about the Swift language not about the UIAlertView.

Any help?

Goppinath
  • 10,569
  • 4
  • 22
  • 45
  • Possible duplicate of http://stackoverflow.com/questions/26941529/swift-testing-against-optional-value-in-switch-case. – Martin R Jan 09 '17 at 10:21
  • @MartinR No, my question is exactly the opposite of the question what you mentioned. – Goppinath Jan 09 '17 at 10:48
  • I don't think so. That *question* is how to match the non-optional `someValue` against the optional `someOptional` and that is exactly what you are asking. The first suggestion in the accepted answer does it the other way around, but the second suggestion `case let val where val == someOptional:` would work in your case as well (and is similar to what Callam suggested below). – Martin R Jan 09 '17 at 10:51
  • @MartinR OK, then can you please combine `case let val where val == someOptional:`with @Callam's suggestion. – Goppinath Jan 09 '17 at 10:58

2 Answers2

2

You could use a where clause to check if alertView is equal to b.

case (_, 1) where alertView == b:

To ensure alertView unwrapped in not nil, just replace the underscore with .some.

case (.Some, 1) where alertView == b:

Or similarly you could let the unwrapped alertView, but this is essentially the same as the above.

case (let .Some(_alertView), 1) where _alertView == b:
Goppinath
  • 10,569
  • 4
  • 22
  • 45
Callam
  • 11,409
  • 2
  • 34
  • 32
  • It works, but it is not satisfying me. There for let me wait for a while and make it as a right answer. Until then a up vote. Thanks. – Goppinath Jan 09 '17 at 10:46
  • @Goppinath thanks for the upvote. What is bothering you exactly? – Callam Jan 09 '17 at 11:21
0

You might try this (using ? in the case) You'll need to add self.b to the tuple that you are switching on:

func alertView(alertView: SPAlertView!, clickedButtonAtIndex buttonIndex: Int) {
    switch (b, alertView, buttonIndex) {
    case (_, a, 0), (_,a,1): // Do something
    case (b?, a, 1): //  <==  b is not optional here (only matches case .Some = b and binds to local variable `b`
    default: break
    }
}
Mac Bellingrath
  • 575
  • 3
  • 9