(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 (separator, terminator) 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
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
Latest end-to-end Learn by Coding Projects (Jupyter Notebooks) in Python and R:
All Notebooks in One Bundle: Data Science Recipes and Examples in Python & R.
End-to-End Python Machine Learning Recipes & Examples.
End-to-End R Machine Learning Recipes & Examples.
Applied Statistics with R for Beginners and Business Professionals
Data Science and Machine Learning Projects in Python: Tabular Data Analytics
Data Science and Machine Learning Projects in R: Tabular Data Analytics
Python Machine Learning & Data Science Recipes: Learn by Coding
R Machine Learning & Data Science Recipes: Learn by Coding
Comparing Different Machine Learning Algorithms in Python for Classification (FREE)
There are 2000+ End-to-End Python & R Notebooks are available to build Professional Portfolio as a Data Scientist and/or Machine Learning Specialist. All Notebooks are only $29.95. We would like to request you to have a look at the website for FREE the end-to-end notebooks, and then decide whether you would like to purchase or not.