Jon Gi Jon Gi - 6 months ago 18
Swift Question

Unable to set query inside if-statement?

Basically I'm attempting to set a specific query in the current table controller depending on the indexpath.row value taken from a previous table controller. So for example,

if indexpath1 == 1
{
let query = CKQuery(recordType: "American", predicate: predicate)
}
else
{
let query = CKQuery(recordType: "Bistro", predicate: predicate)
}

publicDatabase.performQuery(query, inZoneWithID: nil) { (results, error) -> Void in


however, the performquery function comes up with the "use of unresolved indentifier "query".

Do I need to set query to a value before the if-statement to act as a base value that is changed dependant upon the if-statement? Or I am unable to complete this logic?

Answer

It's a basic scope problem, you create a local query instance inside your if, but that doesn't live on to do any good in this world.

var query: CKQuery
if indexpath1 == 1 {
        query = CKQuery(recordType: "American", predicate: predicate)
        }
        else
        {
        query = CKQuery(recordType: "Bistro", predicate: predicate)
        }

        publicDatabase.performQuery(query, inZoneWithID: nil) { (results, error) -> Void in

Or perhaps a bit more elegant:

let recordType = indexpath1 == 1 ? "American" : "Bistro"
let query = CKQuery(recordType: recordType, predicate: predicate)
publicDatabase.performQuery(query, inZoneWithID: nil) { (results, error) -> Void in {
    //...
}