3

Lets say I have two variables, both optionals:

var a:Int? = 42
var b:Int? = 13

I have a condition where it's OK to proceed as long as these are not BOTH currently nil. I thoughtlessly put together something like:

guard let _ = a, let _ = b else { return }

I was absentmindedly thinking the conditions would be OR'ed, rather than AND'ed. Obviously that was wrong. The question then becomes, is there an idiomatic/preferred way to test that? Or do I just regress to the basics:

if a == nil && b == nil { return }

Aside

If I use the message extensions added by this post, then I might happily write something like

guard a.notNil || b.notNil else { return }

Which is about is close as I can come to "make certain (guard) that a is not nil or b is not nil"

Community
  • 1
  • 1
Travis Griggs
  • 21,522
  • 19
  • 91
  • 167

3 Answers3

3

A guard is an if, really, so you can do this the same way. This is clear and uses guard, which seems to be part of the fun. I present OR and AND options so you can pick one.

func doItOr(a: Int?, b:Int?) {
    guard (a != nil || b != nil) else { return }
    print("either A and B is not nil");
}

func doItAnd(a: Int?, b:Int?) {
    guard (a != nil && b != nil) else { return }
    print("both A and B are not nil");
}


doItOr(nil, b: nil)
doItOr(nil, b: 5)
doItOr(4, b: 5) // prints

doItAnd(nil, b: nil)
doItAnd(nil, b: 5)
doItAnd(nil, b: nil)
doItAnd(4, b: 5) // prints
Dan Rosenstark
  • 68,471
  • 58
  • 283
  • 421
1

it's OK to proceed as long as these are not BOTH currently nil

Your question poses two quite different possible conditions, so I will assume, for purposes of discussion, that you mean this one, namely "not both currently nil". Okay, then: "Not" is !. "Both" is &&. So, like this:

guard !(a == nil && b == nil) else {return}
matt
  • 515,959
  • 87
  • 875
  • 1,141
  • You're right and this answers the question, but an `if` statement is preferable in all ways, I think. Except for the word `guard` it's easier to read in every way. – Dan Rosenstark Dec 18 '15 at 18:02
  • 1
    @Yar I don't agree and in any case that isn't what the OP asked (as far as I can tell). – matt Dec 18 '15 at 18:13
0

If you really don't need to bind a or b as non-optionals or discern which of the two is non-nil, I believe the idiomatic approach would still be to use the if statement.

I generally use guard to narrow the specificity of my parameters by binding optionals, downcasting, etc.

You don't seem to be interested in doing that here. You just want to check them, so if seems to appropriately express that.

adpalumbo
  • 3,031
  • 12
  • 12