Basic Syntax for Swift

With all programming languages, Swift comes with its own syntax of declaring variables, functions and so on. Here are some code examples representing the basic syntax for Swift 3.

In order to test the code, it is recommended to use the Xcode playground. This can be opened by opening up Xcode, and choosing the ‘Get started with a playground’ option.

Basic Syntax for Swift

Choose your playground options and continue to the next step.

Basic Syntax for Swift

The next step will involve saving your playground on your computer. When this has been done, you’re ready to begin.

The playground is an area that will allow you to write out code and see the results immediately in the results container at the bottom of the screen.

Basic Syntax for Swift

As seen in the image, variables are declared using the var keyword.

var str = "Hello, playground"
var myVariable = "Some value"

Constants, which are values that are declared that do not change, are set using the let keyword.

let myConstant = "Constant value"

You can print the current value of a constant or variable using the print keyword and placing the constant or variable within a pair of parenthesis.


Empty arrays can be created using the square bracket syntax.

var shoppingList = ["catfish", "water", "tulips", "blue paint"]
// Prints: water

Conditional statements are similar to other programming languages. Note that the round parentheses are not used.

let enteredDoorCode = true
let passedRetinaScan = false
if enteredDoorCode && passedRetinaScan {
} else {
    print("ACCESS DENIED")

Define functions using the func keyword.

In the below example, we have defined a ‘sayHello’ function that take a ‘person’ parameter as a string, and returns a string denoted by the -> String syntax.

func sayHello(person: String) -> String {
    let greeting = "Hello, " + person + "!"
    return greeting

print(sayHello(person: "John"))

Note: This article is based on Swift version 3.