Read ENV into fastfile.swift

I am trying to access ENV variables into fastfile.swift with following

import Foundation
print(ProcessInfo.processInfo["API_TOKEN"])

but getting following error

expressions are not allowed at the top level print(ProcessInfo.processInfo["API_TOKEN"])
value of type 'ProcessInfo' has no subscripts print(ProcessInfo.processInfo["API_TOKEN"])

This code

import Foundation
let api_token = ProcessInfo.processInfo.environment["API_TOKEN"]
print(api_token)

got me

expressions are not allowed at the top level print(api_token)
expression implicitly coerced from 'String?' to 'Any' print(api_token)

All above errors I got while running fastlane command.

what is correct way to do this ?
I just want to pass credentials to fastlane via ENV's

Are you running the file as the main file? That would allow top-level code. For example, if you go to the command line and type swift fast file.swift then you should not encounter that error.

I am running fastlane command in fastlane/ dir inside project dir.
Is there way to make it work with fastlane command ?

Could you detail how to reproduce your exact build environment? I'm not familiar with fastlane, but I assume the "project dir" is the directory of some larger Swift project. So it seems that only compiling a single Swift file won't suffice.

I have iOS project dir with following structure.

.
├── Fonts
├── Gemfile
├── Gemfile.lock
├── Jenkinsfile
├── HUBAPICommunicator
├── HUBDataModels-iOS
├── HUBModulesStates
├── LICENSE
├── Director
├── Director.xcodeproj
├── Director.xcworkspace
├── DirectorTests
├── DirectorUITests
├── PaintCodeGraphics
├── Podfile
├── Podfile.lock
├── README.md
├── Views
├── apple-app-site-association
├── fastlane
└── test_output

inside fastlane I have

$ tree fastlane/ -L 1
fastlane/
├── Appfile.swift
├── Fastfile.swift
├── FastlaneRunner
├── Matchfile
├── Matchfile.swift
├── Pluginfile
├── report.xml
└── swift

I have iOS project dir in which I have all code related to app and then I have fastlane dir with Appfile.swift, Fastfile.swift, FastlaneRunner, Matchfile, Matchfile.swift, Pluginfile, report.xml, swift (dir).

Fastfile.swift has fastlane function for build and deploy.

In fastlane/Fastfile.swift I want to read credentials from ENV variables and pass to required functions for auth.

Try un-checking Fastfile.swift from the app's target in Xcode. Then it won't build as part of the Xcode project. After that, run swift fastlane/Fastfile.swift from the command line.