0

I have been trying to write a simple function for adding two variables.

func add(X: Int?, Y: Int?) -> Int? {
    guard let X != nil, Y != nil else
    { return nil }
    return X + Y
}

I keep getting the following 2 error messages:

"Pattern matching in a condition requires the 'case' keyword"

and

"Variable binding in a condition requires an initializer"

Can someone help me fix this code?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
estelyk
  • 25
  • 9
  • 1
    You should be reading the documentation on optional binding: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID333 – Cristik Mar 14 '18 at 18:46
  • Or a summary here: https://stackoverflow.com/questions/24128860/how-is-optional-binding-used-in-swift – Cristik Mar 14 '18 at 18:47

1 Answers1

3

You want your guard to be:

guard let X = X, let Y = Y else {
    return nil
}

When using guard let you need an assignment, not a condition. And each variable needs its own let.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • don't forget about the naming conventions `guard let x = x, let y = y else {` and `func add(x: Int?, y: Int?) -> Int? {` – Leo Dabus Mar 14 '18 at 19:12
  • 1
    @LeoDabus Yeah. I just went with the OP's code. I get tired of repeating myself over and over :) – rmaddy Mar 14 '18 at 19:13