Search code examples
iosswiftrealm

Realm swift beginGroup/endGroup equivalent


What is the equivalent of beginGroup/endGroup (kotlin) in swift? I need to rebuild this query below in swift. I have read the documentation, but I couldn't recreate such query.

fragment.realm.where(Item::class.java)
  .`in`("type", Item.Type.values().map { it.name }.toTypedArray()) 
  .apply {
      isEmpty("section")
      or()
      beginGroup()
      // Do something
      endGroup()
  }
  .sort("sortScore", Sort.DESCENDING)
  .findAll()

Solution

  • The meaning of beginGroup and endGroup are just "parentheses", so that you can group the sub-expressions in your query. In Realm Swift, you can either write queries in Swift syntax after version 10.19 (because of the Query struct that supports dynamic member lookup and operator overloading), or using NSPredicate syntax. Both of these syntaxes supports using parentheses to group expressions directly, so you can just write something like this:

    // version 10.19+
    let items = realm.objects(Item.self).where { item in
        item.type.in(ItemType.allCases.map(\.rawValue)) &&
        item.section == "" ||
        ( // this parenthesis is what beginGroup translates to
            /* do something */
        ) // this parenthesis is what endGroup translates to
    }.sorted(by: \.sortScore, ascending: false)
    

    That said, as far as I can see, this pair of parentheses is unnecessary. Anything you put in "do something" will have higher or the same precedence as || anyway, so the predicate will have the same result whether or not you put the parentheses.

    Side note: the documentation you found is a legacy version of Realm Swift. This is the new documentation.