title: Test for presence or absence of a record in CloudKit with Swift 2
body: <p>I am writing a tvOS app. I want to test to see if there's a record in CloudKit database. </p>
  
  <p>I am trying to do this by seeing if there is a record with an specific <code>eventID</code>.</p>
  
  <p>Ideally, I want to call a function that returns true or false:</p>
  
  <pre><code>if isEventInWatchListFile(eventID) {
   // ... do things
  }
  </code></pre>
  
  <p>What I have tried is the following:</p>
  
  <pre><code> var results = [AnyObject]()
   var onList:Bool?
  
   . . .
  
      func isEventInWatchListFile(eventID: String) -&gt; Bool {
  
          let container = CKContainer(identifier: "the container")
          let privateDB = container.privateCloudDatabase
  
          let predicate = NSPredicate(format: "eventID == %@",eventID)
          let query = CKQuery(recordType: "UserWatchlist", predicate: predicate)
  
          privateDB.performQuery(query, inZoneWithID: nil) { results , error in
              guard let results = results else {
                  // error handler to come
                  return
              }
  
              if results[0]["eventID"] != nil {
  
                self.onList = true
  
              } else {
  
                self.onList = false
              }
          }
  
          return self.onList!
      }
  </code></pre>
  
  <p>This crashes with "fatal error: unexpectedly found nil while unwrapping an Optional value". I think this is because <code>onList</code> is locked up in a closure. I have two questions:</p>
  
  <p>1) Is it possible to pass out <code>onList</code> to the <code>return</code> statement, and, if so, how? I've read up on closures in Swift, but not sure how to apply what I've read.</p>
  
  <p>2) Is there a better way to do the test I want to do? My approach seems clunky to me.</p>
  
  <p>I am very new to iOS and Swift. Any help greatfully received. </p>