title: How can I set up an NSPredicate to sum the values of properties inside dictionaries in an array of dictionaries in iOS?
body: <h2>Q: How can I set up an <em>NSPredicate</em> to sum the values of properties inside dictionaries in an array of dictionaries in iOS?</h2>
  
  <p><em>Note: answer must be a single string used in a format argument of an NSPredicate object. As in:</em>
  <code>var pred1:NSPredicate = NSPredicate.init(format: *ANSWER*)</code></p>
  
  <hr>
  
  <p>Suppose I have the following dictionary:</p>
  
  <pre><code>var ticketState:Dictionary =
  [
      "orderTotal":1.2,
      "payments":
      [
          [
              "authCode":"12345",
              "isVoid":"false",
              "amount":1.0
          ],
          [
              "authCode":"54321",
              "isVoid":"false",
              "amount":0.2
          ]
      ],
      "associatedWithReturn":false
  ]
  </code></pre>
  
  <p>Now I want an <code>NSPredicate</code> to check if all the amounts sum up to equal the order total. </p>
  
  <p>Something like:</p>
  
  <pre><code>var cond1:String = "sum($payments[].amount == $orderTotal)"
  </code></pre>
  
  <p>Note: I <em>cannot</em> use array filtering or a second predicate.</p>
  
  <p>I can access the first payment amount like this:</p>
  
  <pre><code>var cond1:String = "$payments[1].amount &gt; 0" //works, returns true
  </code></pre>
  
  <p>This will return true. I just want to check that the sum of all the amounts in payments equals the order Total. This should be a simple operation defined by a single predicate. </p>
  
  <p>How do I write a one-line NSPredicate declaration that accomplishes this?</p>
  
  <hr>
  
  <p><em>Note: there is a very specific reason I need it to be a one-line, single NSPredicate initialization format string. But that's an implementation detail; don't worry about it, because someone else might have a different reason than me for needing the same type of initialization.</em></p>