Swift Input and Output

In Swift, we can use various functions to handle input and output operations. Input operations are used to get data from the user, while output operations are used to display data to the user. In this article, we will explore some common functions used for input and output in Swift with examples and output.

Printing to the Console

The print() function is used to display output to the console. It takes one or more values as input and displays them to the console. Here is an example:

1print("Hello, world!")

Output: Hello, world!

We can also print the value of a variable:

1var x = 45 2print(x)

Output: 45

We can print multiple values by separating them with a comma:

1var name = "Max" 2var age = 24 3print("My name is", name, "and I am", age, "years old.")

Output: My name is Max and I am 24 years old.

We can also use string interpolation to include variables in a string:

1var city = "New York" 2var temperature = 77.5 3print("The temperature in \(city) is \(temperature) degrees Fahrenheit.")

Output: The temperature in New York is 77.5 degrees Fahrenheit.

Getting Input from the User

To get input from the user, we can use the readLine() function. This function reads a line of text from the console and returns it as a string. Here is an example:

1print("What is your name?") 2var name = readLine() 3print("Hello, \(name!)!")


1What is your name? 2Bob 3Hello, Bob!

Note that we use the exclamation mark (!) to unwrap the optional value returned by readLine().

We can also convert the user input to a specific data type using optional binding:

1print("What is your age?") 2if let age = readLine(), let ageInt = Int(age) { 3 print("Next year, you will be \(ageInt + 1) years old.") 4} else { 5 print("Invalid input.") 6}


1What is your age? 221 3Next year, you will be 22 years old.

In this example, we use optional binding to unwrap the optional string returned by readLine() and convert it to an integer using the Int() initializer. If the conversion is successful, we print a message using the user's age.