Xcode environment setup for swift practise on HackerRank

Ajay Singh Thakur
2 min readMay 16, 2021

--

Those who are familiar with hacker rank and other similar platforms for coding practice have faced the input-output format issue in swift.

Like many iOS, macOS, or other apple platform developers we rarely deal with console Input/Output or with an environment variable.

The one way to interact with console input is readLine().

func readLine(strippingNewline: Bool = true) -> String?

Once you read the line from the console you can convert it to other Data types like Int, Double, etc as per your need.

This article “Swift reading input” contains a lot of helper methods to read a different type of input from the console.

The other roadblock you will notice in some of the hacker-rank problems you have to write output to a file and whose output file-path has to be taken from an environmental variable, see example code below.

Sample Code

ProcessInfo.processInfo.environment[“OUTPUT_PATH”] is a singleton object used to access the environment variable to get the output file path.

Let’s get started.

  1. Open Xcode -> Create a new Xcode project -> macOS -> Command line tool.
  2. Enter Product Name, select team, and select Language as swift the save to project to your desired location.
  3. Open main.swift file copy the above code and run.
  4. Enter input arrCount and space-separated array element’s arr.
  5. After entering input the code will crash at the line. let stdout = ProcessInfo.processInfo.environment[“OUTPUT_PATH”]! , This is because environment variable is not set.
  6. To set env var, Open the scheme manager. Select Product -> Scheme -> Manage Schemes… from the toolbar.
  7. Click on Edit Scheme…, select option Run under Environment Variable click on add icon.
  8. Enter name: OUTPUT_PATH and value: $(SRCROOT)/output.txt.

That it. now run the project and enter the input value, your output will be stored in the output.txt file which is placed under your project source directory.

A short video of the above steps for those who understand by visuals.

--

--

Ajay Singh Thakur
Ajay Singh Thakur

Written by Ajay Singh Thakur

SDE with expertise in iOS, also knows android and azure data engineer

No responses yet