Swift "Hello World" Program

In this article, you will dive into Swift programming by writing a "Hello, World!" program. You'll learn the basic syntax for a working Swift program.

A "Hello, World!" is a computer program that is often used to illustrate the basic syntax of a programming language with a working program. This program outputs Hello, World! on the screen.

If you want to run this program in your computer, make sure that Swift and Xcode is properly installed. For that, check How to run Swift on your computer?

Let's explore how to create Swift "Hello, World!" program.


"Hello, World!" program on Xcode Playground

// Hello, World! Program
import Swift
print("Hello, World!")

Copy the exact code onto the Xcode Playground.

When you run the program, the output will be:

Hello, World!

How Swift "Hello, World!" Program Works?

  1. // Hello, World! Program

    In Swift, any line starting with two slashes // is a comment. They are completely ignored by the compiler. Comments are intended for person reading the code to better understand the intent and functionality of the program. If you want to learn more about comments visit Swift Comments.
     
  2. import Swift

    import keyword allows you to access all the symbols defined inside a framework.For now, just remember this line is required to use print("Hello, World!") in our program. You’ll learn more about it in the later tutorials.
     
  3. print("Hello, World!")

    The above line is called a function in Swift. More specifically, a print function.

    In swift, print means "show on the screen". The above code prints the string inside quotation marks, i.e "Hello, World!" on the screen. You’ll learn more about functions and how they work in later tutorials.

"Hello, World!" Program on Terminal

  1. Open Terminal
  2. Type swift and press enter (return). This will give you a welcome message as Welcome to Apple Swift version x.x.x.
  3. Type print("Hello, World!")

When you hit the enter (or return) key, the output will be :

Hello, World!

Things to remember

  1. If you are familiar with other programming languages like C, C++, Java you need to add semicolon (;) at the end of each statement. However, it's optional to add semicolon ";" at the end of statement in Swift. It is also not recommended.

    If you need to add multiple statements in a single line, you must include ";" at the end of the statement.

    Example:
    print("Hello,");print("World!")
    
  2. If you wish, you can remove the line import Swift from your program because it’s automatically included in the playground for you.

Don’t worry if you don’t understand some concepts in this tutorial for now, we’ll discuss them in detail in our later tutorials.