title: How to return result of HKStatisticsQuery to a variable in Swift 2?
body: <p><strong>UPDATED at bottom on 01/30/16 @ 7:40PM EST</strong></p>
  
  <p>So I'm trying to run a StatisticsQuery to get the total <code>DistanceRunningWalking</code> of the day stored in HealthKit and then store the results of that query in a variable, to be worked with later. The query seems to be working fine, as I've tested printing the results of the query (<code>totalDistance</code>) to a Label from within the function. The problem I'm running into is when trying to save the result to a variable instead.</p>
  
  <p>Here is the code in my HealthKitManager.swift file:</p>
  
  <pre><code>import HealthKit
  
  class HealthKitManager {
  
  class var sharedInstance: HealthKitManager {
      struct Singleton {
          static let instance = HealthKitManager()
      }
  
      return Singleton.instance
      }
  
      let healthStore: HKHealthStore? = {
          if HKHealthStore.isHealthDataAvailable() {
              return HKHealthStore()
          } else {
              return nil
          }
      }()
  
      let distanceCount = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning)
  
      let distanceUnit = HKUnit(fromString: "mi")
  
  }
  </code></pre>
  
  <p>Code at top of ViewController: (this is the variable I'd like to save to)</p>
  
  <pre><code>let healthKitManager = HealthKitManager.sharedInstance
  
  //Set up variable to contain result of query
  var distanceTotalLength:Double?
  </code></pre>
  
  <p>Code in <code>viewDidLoad</code>:</p>
  
  <pre><code>//Run the function
  requestHealthKitAuthorization()
  
  //Set value of variable to query result
  distanceTotalLength = queryDistanceSum()
  </code></pre>
  
  <p>Code in body of ViewController:</p>
  
  <pre><code>func requestHealthKitAuthorization() {
      let dataTypesToRead = NSSet(objects: healthKitManager.distanceCount!)
      healthKitManager.healthStore?.requestAuthorizationToShareTypes(nil, readTypes: dataTypesToRead as NSSet as? Set&lt;HKObjectType&gt;, completion: { [unowned self] (success, error) in
          if success {
              self.queryDistanceSum()
          } else {
              print(error!.description)
          }
          })
  }
  
  func queryDistanceSum() {
      let sumOption = HKStatisticsOptions.CumulativeSum
      let startDate = NSDate().dateByRemovingTime()
      let endDate = NSDate()
      let predicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate: endDate, options: [])
  
      let statisticsSumQuery = HKStatisticsQuery(quantityType: healthKitManager.distanceCount!, quantitySamplePredicate: predicate, options: sumOption) {
          [unowned self] (query, result, error) in
          if let sumQuantity = result?.sumQuantity() {
              dispatch_async(dispatch_get_main_queue(), {
              let totalDistance = sumQuantity.doubleValueForUnit(self.healthKitManager.distanceUnit)
              self.distanceTotalLength = totalDistance
              })
          }
      }
      healthKitManager.healthStore?.executeQuery(statisticsSumQuery)
  }
  </code></pre>
  
  <p>On the last line <code>return (distanceTotalLength)!</code> I'm getting an error when launching the application which reads <code>fatal error: unexpectedly found nil while unwrapping an Optional value</code>. I've realized that this is most likely a problem dealing with scope (although I may be doing something else wrong, so please point anything out) but I'm failing to see/find the solution to the issue on my own.</p>
  
  <p>Any help with this would be greatly appreciated, so thanks in advance!</p>
  
  <p><strong>UPDATE: 01/30/16 @ ~7:40PM EST</strong></p>
  
  <p>Okay, so I've been working on trying to fix this myself and I've made a discovery: The code is definitely working. By assigning an initial value of <code>0</code> to <code>distanceTotalLength</code> at the top of the ViewController, I was able to run the application without getting the fatal error. However, when I then tried passing the value of <code>distanceTotalLength</code> to another view via a prepareForSegue function, I realized that it is being assigned after all. When I go to that view, it isn't using the initial value of <code>0</code>, but the result of the query instead.</p>
  
  <p>The way I tested this out was by setting up the variable: <code>var distanceTotalLength:Double = 0</code> at the very top of my viewController, before <code>viewDidLoad</code> Then inside <code>viewDidLoad</code> I assigned the value to a label using <code>distanceLabel.text = String(distanceTotalLength)</code> and as I said, the label ends up reading <code>0</code>. But when I transition to another view, passing the value of <code>distanceTotalLength</code> and printing the value out there, it works. On this second screen, it prints the result of the query, not <code>0</code>.</p>
  
  <p>So I'm assuming that the problem is that the query runs and then assigns the value AFTER the view has already loaded in with all of it's predefined values. Unfortunately, this is where I get stuck again. Anyone out there know how to help me out now that I've gotten this far?</p>