0

I don't understand why I am getting this error. I don't see anything wrong with the code. Please help!! Thanks!

      guard reason == .completed else { return }
 ***guard let symptomTrackerViewController = symptomTrackerViewController***,
let event = symptomTrackerViewController.lastSelectedAssessmentEvent else { return }


let carePlanResult=carePlanStoreManager.buildCarePlanResultFrom(taskResult: taskViewController.result)

   carePlanStoreManager.store.update(event, with: carePlanResult, state: .completed) {
        success, _, error in
        if !success {
            print(error?.localizedDescription)
        }
    }
}

}

  • Can you show on what line you are getting this error? – JPetric Dec 08 '16 at 19:33
  • This is weird: `guard let symptomTrackerViewController = symptomTrackerViewController` - why would you unwrap `symptomTrackViewController` into the same variable ? It doesn't make sense. My guess: either `symptomTrackerViewController` or `symptomTrackerViewController.lastSelectedAssessmentEvent` are not optional ( at least one of them can't be nil ) – Randy Dec 08 '16 at 19:36
  • So what would it look like? In your opinion – Khalid Mohamed Dec 08 '16 at 19:44

2 Answers2

1

The syntax

if let someVal = someVal {
  //Inside the braces someVal is unwrapped
}

Works when the variable name is the same on both sides of the equal sign.

However, the code

guard let someVal = someVal else {
  return
}

Is not legal. I believe the reason the first form, the if let conditional binding, lets you unwrap an optional using the same name, is that the reassignment is only valid inside the inner level of scope created by the braces for the if statement.

In contrast, the guard statement does not put braces around the code that gets executed when the optional unwrapping succeeds. There's no inner scope in which the new definition of someVar is valid.

The second part of it is that it sounds like your symptomTrackerViewController is not an optional. If symptomTrackerViewController is not an optional then any code that attempts to unwrap it (if let, guard let, and using ? and !) will fail.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
0

Either symptomTrackerViewController or symptomTrackerViewController.lastSelectedAssessmentEvent is not an optional.

  1. Check if your symptomTrackerViewController is optional. If it is not optional it can never be nil so you can remove it from the guard.

  2. Try changing guard to

    guard let symptomTrackerVC = symptomTrackerViewController, let event = symptomTrackerViewController.lastSelectedAssessmentEvent else { return }

When you are using if let something = somethingElse, somethingElse must be an optional.

JPetric
  • 3,838
  • 28
  • 26