Xcode environment setup for swift practise on HackerRank
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.
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.
- Open Xcode -> Create a new Xcode project -> macOS -> Command line tool.
- Enter Product Name, select team, and select Language as swift the save to project to your desired location.
- Open main.swift file copy the above code and run.
- Enter input
arrCount
and space-separated array element’sarr
. - 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. - To set env var, Open the scheme manager. Select Product -> Scheme -> Manage Schemes… from the toolbar.
- Click on Edit Scheme…, select option Run under Environment Variable click on add icon.
- 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.