How to create a loop in Cadence

Daniela
Daniela
  • Updated

In Cadence, you can create a loop to iterate over paths in an account.

  • Here are the steps to do that:
    If you want to loop over public paths, you need a PublicAccount
  • If you want to loop over private/storage paths, you need an AuthAccount

You need to define an “iteration function” to tell Cadence what to do on each path.

In the function, on each iteration, you return true if you want to continue looping, or false if you want to stop.

Then, you pass the “iteration function” to a different function that lets you loop over paths.

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

Here's a simple example:

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 false to stop iterating
return true
}
}

In this example, the iteration function checks if the type of the item at the current path is a string. If it is, it logs a message and stops iterating. Otherwise, it continues to the next iteration.

For more details, you can refer to Flow's Academy on Looping Over an Account.