Docs Menu

Call a Function - Swift SDKicons/link.png

On this page

  • Call a Function by Name
  • Async/Await Call a Function

Consider a Realm function named concatenate that takes two arguments, concatenates them, and returns the result:

// concatenate: concatenate two strings
exports = function(a, b) {
return a + b;

To execute a function from the iOS Client SDK, use the functions object on the currently logged-in user.

The functions object has dynamic members corresponding to functions. In this case, functions.concatenate() refers to the concatenate function. Pass a BSONArray of arguments. The trailing closure is the completion handler to call when the function call is complete. This handler is executed on a non-main global DispatchQueue.

New in version 10.16.0.

If you're using Swift 5.5 with an iOS target of 15.0 or higher, you can use the async/await versions of the User.function methods.

func testAsyncCallFunction() async {
let app = App(id: YOUR_REALM_APP_ID)
// ... log in ...
let user = app.currentUser!
do {
// The dynamic member name `concatenate` is directly associated with the
// function name. The first argument is the `BSONArray` of arguments to be
// provided to the function - in this case, a string that represents a
// username and a string that represents an email domain.
let concatenatedString = try await user.functions.concatenate([AnyBSON("john.smith"), AnyBSON("")])
print("Called function 'concatenate' and got result: \(concatenatedString)")
assert(concatenatedString == "")
} catch {
print("Function call failed: \(error.localizedDescription)")
Give Feedback
MongoDB logo
© 2021 MongoDB, Inc.


  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2021 MongoDB, Inc.