How to create a loop in Cadence

Daniela
Daniela
  • Updated

In Cadence, you can create a loop to iterate over certain data structures or paths.

Here's an example of how to loop over the storage paths inside of an account:

pub fun main(user: Address) {
// 1. Get the AuthAccount
let authAccount: AuthAccount = getAuthAccount(user)

// 2. Define an iteration function
let iterationFunction = fun (path: StoragePath, type: Type): Bool {
if type == Type<String>() {
log("I found a string! Done looping.")
// 3. Return false to stop iterating
return false
}
// 3. Return true to continue iterating
return true
}
...
}

In this example, an iteration function is defined that checks the type of each item in the storage paths. If the type is a string, it logs a message and returns false to stop the iteration. Otherwise, it returns true to continue the iteration.

For more complex looping, such as looping over every path and discovering some information, you would need to define an "iteration function" to tell Cadence what to do on each path. Then, you pass the "iteration function" to a different function that lets you loop over paths.

  • For public paths, you use forEachPublic
  • For storage paths, you use forEachStored
  • For private paths, you use forEachPrivate

For more information, you can refer to the Intermediate Cadence Course on the Flow Academy.