How do you use for loop in Sway?

Topic discussion checklist

  • Run $ fuelup show and add the output below
fuelup show
Default host: aarch64-apple-darwin
fuelup home: /Users/danielchew/.fuelup

installed toolchains
--------------------
beta-5-aarch64-apple-darwin
latest-aarch64-apple-darwin (default)
nightly-2024-01-24-aarch64-apple-darwin (override)

active toolchain
----------------
nightly-2024-01-24-aarch64-apple-darwin (override), path: /Users/danielchew/Code/pyth-fuel/fuel-toolchain.toml
  forc : 0.49.1+nightly.20240124.c43b57fd3d
    - forc-client
      - forc-deploy : not found
      - forc-run : not found
    - forc-crypto : not found
    - forc-doc : not found
    - forc-explore : 0.28.1+nightly.20240124.4bb7392eed
    - forc-fmt : not found
    - forc-lsp : not found
    - forc-tx : not found
    - forc-wallet : 0.4.2+nightly.20240124.e0c391f880
  fuel-core : 0.22.0+nightly.20240124.a0b022d5ea
  fuel-core-keygen : 0.22.0+nightly.20240124.a0b022d5ea
  • Detailed steps to recreate issue
    In the Sway book it says that you can use a for loop like this
for element in vector.iter() {
    sum += element;
}

but I’ve tried to do this

    // Mark all old data sources as invalid
    for data_source in old_data_sources.iter() {
        storage.is_valid_data_source.insert(data_source, false);
    }

where old_data_sources is a StorageVec but I am getting:

error
   --> /Users/danielchew/Code/pyth-fuel/pyth-contract/src/main.sw:753:5
    |
751 |
752 |     // Mark all old data sources as invalid
753 |     for data_source in old_data_sources.iter() {
    |     ^^^ Identifiers cannot be a reserved keyword.
754 |         storage.is_valid_data_source.insert(data_source, false);
755 |     }
    |
____

I have been using while loops instead to bypass this but appreciate if I can get any help on this.

Hii @cctdaniel, I think for is not supported in sway in current version of forc 0.49.3 but enable to use while

Code example:

Doc reference: