Search code examples
swiftcore-datanspredicate

Swift - Is there a way to include single quotes (') in a concatenated string?


I have already searched for answers and whatever I tried unfortunately did not work. My case is as follows: I have an array of keywords and I am building an NSPredicate in order to filter data from CoreData. The code below:

var strKeywordsOrFilter = "(1 == 1)" //just an initial {true} statement to assist with the OR conditional
for intIndex in 0...pInputWords.count - 1
{
    let strKeyword = "'" + pInputWords[intIndex] + "'"
    strKeywordsOrFilter = strKeywordsOrFilter + " OR (imageDescr CONTAINS[c] " + strKeyword + ")"
}

imageDescr is one of the entity attributes in my CoreData. What I want to accomplish is to create a concatenated string of OR conditions for as many keywords exist in the array pInputWords. When I debug print the variable strKeywordsOrFilter it does NOT contain any backslashes before any single quote character, e.g.

(1 == 1) OR (imageDescr CONTAINS[c]  'camping') OR (imageDescr CONTAINS[c]  'lake')

but the same variable when it reaches the "predicate" command, it contains backslashes before every single quote, e.g.

(1 == 1) OR (imageDescr CONTAINS[c]  \'camping\') OR (imageDescr CONTAINS[c]  \'lake\')

I have tried a number of workarounds but nothing seems to get rid of the "\". Any help would be appreciated because I am really stuck!


Solution

  • No need to manually construct your query, or worry about quotes. You can use a compound predicate instead and standard predicate formatting (%@ for values and %K for keys):

    let predicates = pInputWords.map { word in
        NSPredicate(format: "imageDescr CONTAINS[c] %@", word)
    }
    
    let finalPredicate = NSCompoundPredicate(orPredicateWithSubpredicates: predicates)
    
    // Which gives:
    // imageDescr CONTAINS[c] "camping" OR imageDescr CONTAINS[c] "lake"
    

    ps. Your query string produces the same result when fed to a predicate, which seems to be fine