Group Group Group Group Group Group Group Group Group

What is the benefit of using file handle to write data to stdout?

I just curious about the swift code template: e.g.

import Foundation

// Complete the birthdayCakeCandles function below.
func birthdayCakeCandles(ar: [Int]) -> Int {


let stdout = ProcessInfo.processInfo.environment["OUTPUT_PATH"]!
FileManager.default.createFile(atPath: stdout, contents: nil, attributes: nil)
let fileHandle = FileHandle(forWritingAtPath: stdout)!

guard let arCount = Int((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!)
else { fatalError("Bad input") }

guard let arTemp = readLine() else { fatalError("Bad input") }
let ar: [Int] = arTemp.split(separator: " ").map {
    if let arItem = Int($0.trimmingCharacters(in: .whitespacesAndNewlines)) {
        return arItem
    } else { fatalError("Bad input") }

guard ar.count == arCount else { fatalError("Bad input") }

let result = birthdayCakeCandles(ar: ar)

fileHandle.write(String(result).data(using: .utf8)!)
fileHandle.write("\n".data(using: .utf8)!)

I can make the code work with just


and without any code to create FileHandle to the stdout, I just can’t see the point to make those code overcomplicated.

off topic:
how to pass the environment variables when I run the code from command line?
I am failed to make it work using the following command:

OUTPUT_PATH=`pwd` && xcrun swift abc.swift

Hi @ryanlee and welcome to the community!

I’m answering your off topic, ProcessInfo in Foundation is your friend for anything related to the system processes. You generally work with its singleton: processInfo.

In particular, you are looking for the environment array:

if let dbsecret = ProcessInfo.processInfo.environment[“dbpassword”] {
// your code here