Swift programming for Beginners – Swift Basic Input and Output

(Swift for Beginners)

Swift Basic Input and Output

In this article, you will learn different ways to display output and get input in Swift.

Swift Basic Output

You can simply use print(_:separator:terminator:) function to send output to standard output (screen). See Swift function article to learn about functions in Swift.

The function print(_:separator:terminator:) accepts three parameters.

  • items: Items to print in the console. It can accept more than one item.
  • separator: A string to print between each item. The default is a single space (" ").
  • terminator: The string to print after all items have been printed. The default is a newline ("n").

 

Since, last two parameters (separatorterminator) has default values already specified, it isn’t mandatory to use them while calling the print function.


Example 1: Printing to the screen using simple print() function

print("Hello, World!")
print("I love Swift.")

When you run the program, the output will be:

Hello, World!
I love Swift.

In the above program, print("Hello, World!") outputs string literal Hello, World! in the console.

You can see it also changes the line (adds a line break) when printing “I love Swift.” because print method’s parameter terminator has a default value n (new line).

So, the statement print("I love Swift.") outputs the message in new line.


Example 2: Printing constants, variables and literals

var helloMsg = "Hello, World!"
print(helloMsg)
print(123.45)

When you run the program, the output will be:

Hello, World!
123.45

You can print value of variable or constant by adding variable or constant name directly in the print function. In the above program print(helloMsg) outputs the value Hello, World! of the variable helloMsg.

You can also insert literals in print statement. In the statement, print(123.45), it takes an floating point literal 123.45 without the double quote and prints it.


Example 3: Printing without a link break using terminator parameter

If you want to print without a line break, you need to pass an empty string in the terminator parameter of the print function as:

print("Hello, World!", terminator: "")
print("I love Swift.")
print("I also love Taylor Swift.")

When you run the program, the output will be:

Hello, World!I love Swift.
I also love Taylor Swift.

In the above program, terminator is the string that is printed after all items has been printed.

We have passed an empty string as the terminator (default is a newline n). So, the first statement prints without adding a new line and statement print("I love Swift.") displays message in the same line.

Since, print("I love Swift.") function adds a line break, the statement print("I also love Taylor Swift") outputs in a new line.


Example 4: Printing multiple items using single print function

You can also print multiple items in a single print statement and add separator between those items as:

print("Hello, World!", 2020, "See you soon", separator: ". ")

When you run the program, the output will be:

Hello, World!. 2020. See you soon

In the above program, we have added different data types in the print statement separated by a comma.

The items to print are string Hello, World!, int 2020 and string See you soon.

We have also passed "." value in separator parameter. This inserts the separator (dot .) between each items. So you can see the output separated by . character followed by a space.


Example 5: Printing multiple lines

If you want to print in multiple line with a single print statement, you can use escape sequence r known as carriage return in the print statement as:

print("Hello, rWorld!")

When you run the program, the output will be:

Hello, 
World!

Example 6: Printing multiple lines using triple quotes

In Swift, there is a better way to output multiline message in a single print statement. You have to use multiline string literal. This is done by adding characters inside multiline string literal using triple quotes as

print("""
Hello,
World!
""")

When you run the program, the output will be:

Hello,
World!

Example 7: Printing variables using string interpolation

You can also add value of a variable or constant into the string literal by using string interpolation, i.e. wrapping variable in a pair of parentheses, prefixed by a backslash ().

var helloMsg = "Hello, World!"
print("I have a message (helloMsg)")

When you run the program, the output will be:

I have a message Hello, World!

The statement print("I have a message (helloMsg)") inserts the value of variable helloMsg by wrapping it as (helloMsg) in string literal. Therefore, the statement outputs I have a message Hello, World! on the screen.


Swift Basic Input

If you want to take input from user in Swift, you cannot do it in Xcode playground without using UIKit framework.

However, using Swift framework, you can create a Command Line Application in Xcode that takes input from an user. You can see Swift Command Line Application article for creating command line application using Xcode.

Here’s the code you can use to get input from user.

Example 8: Taking input from the user using readLine()

print("Please Enter your favorite programming language", terminator: ".")
let name = readLine()
print("Your favorite programming language is (name!).")

When you run the program, the output will be:

Please Enter your favorite programming language.
Swift
Your favorite programming language is Swift.

In the above program, the print function outputs Please Enter your favorite programming language. in the debug area. The statement let name = readLine()waits for user input in the debug area.

If you type “Swift” and press enter, the readLine function assigns that string to constant name and displays the output as Your favorite programming language is Swift.

Since the readLine function returns an optional string, we have forcefully unwrapped the constant as name! in the statement print("Your favorite programming language is (name!)").

You’ll learn more about optionals in the article: Swift Optionals.

 

Swift programming for Beginners – Swift Basic Input and Output

 

Personal Career & Learning Guide for Data Analyst, Data Engineer and Data Scientist

Applied Machine Learning & Data Science Projects and Coding Recipes for Beginners

A list of FREE programming examples together with eTutorials & eBooks @ SETScholars

95% Discount on “Projects & Recipes, tutorials, ebooks”

Projects and Coding Recipes, eTutorials and eBooks: The best All-in-One resources for Data Analyst, Data Scientist, Machine Learning Engineer and Software Developer

Topics included: Classification, Clustering, Regression, Forecasting, Algorithms, Data Structures, Data Analytics & Data Science, Deep Learning, Machine Learning, Programming Languages and Software Tools & Packages.
(Discount is valid for limited time only)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.

Learn by Coding: v-Tutorials on Applied Machine Learning and Data Science for Beginners

Please do not waste your valuable time by watching videos, rather use end-to-end (Python and R) recipes from Professional Data Scientists to practice coding, and land the most demandable jobs in the fields of Predictive analytics & AI (Machine Learning and Data Science).

The objective is to guide the developers & analysts to “Learn how to Code” for Applied AI using end-to-end coding solutions, and unlock the world of opportunities!