Swift, a programming language released by Apple in 2014, has quickly become one of the fastest growing languages in history. If you’re interested in building apps for macOS or iOS, Swift is, in my opinion, the best language of choice.

In this tutorial, we’ll familiarize ourselves with the basic operations of Swift and practice with some related examples. Let’s get started!

The installation

Swift’s version for Mac, Windows and Linux is 5.4.1. Swift is easy to install using Xcode, Apple’s free workflow for desktop and native iOS development.

You can download Xcode from the App Store on macOS or the Swift website. If you are using Windows or Linux, download and install Swift from its official website.

If you don’t want to install Swift on your computer, you can try Swift’s online playground.

Open an Xcode Playground

Once you have Swift installed on your computer, use Xcode to open up a Playground where you can start writing your code.

The data type

We need to know which data types are supported in Swift to see what we can accomplish. We will use the following six data types.

The data type example On behalf of purpose
character sw A 16-bit Unicode character Single character editing
string swift language The text data Save, update, or modify a text/message
symbol 5.- 5 An integer Represents any integer
Float 5.5.5.5 32-bit floating point number Represents a 32-bit floating point number
dual 5.5.5.5 64-bit floating point number Represents a 64-bit floating point number
Bool truefalse Represent state (true/false) Provides true/false values for use in our program.

variable

It takes a lot of data to write a program. Variables provide a way to mark data, making it easier to modify and reference.

A variable structure

We will format a variable using the following structure: Keyword variableName:dataType. You can see the structure used in the code block below.

var name:String

Copy the code

When we define a variable using the above structure, we do not initially put any data in the variable. Let’s add data to the variable, changing it from a NULL, which is a null value in programming, to a string.

var name:String = "nerdjfpb"

Copy the code

Later, we can refer to the above code as needed to access the data. For example, print(name) will display nerdjfpb in the Playground console. You can think of printing things as displaying results. We can see what’s in the name.

We can easily change the value of the variable.

name = "Nerd Jfpb"

Copy the code

When writing with Swift, we don’t need to specify the data type when we start writing its value. For example, in the following code, Swift understands that the name is a string.

var name = "nerdjfpb" 

Copy the code

If we write down the code block above, we will receive an error. Because Swift is a typed language, we cannot change the data type of a variable.

name = 5

Copy the code

Imagine you want to programmatically refer to a variable, but don’t want to change its value. Swift provides a specific way to reference variables.

Reference variables

To reference a variable, we will use the following structure: Keyword(let) variableName dataType = Value, as you can see in the following example.

let ownerName = "Nerdjfpb"
Copy the code

We can only define the value of ownerName once, and we cannot change it. This value will remain the same throughout the program.

The operator

To use Swift, we need to understand these basic operators.

Comparison operator

The operator example explain
= =(equal to
to) variable1 == variable2 Returns true if the variables are equal
! =(don’t
Equal to) variable1 ! = variable2 Returns if the variables are not equal
True.
>(greater than
Ratio) variable1 > variable2 Returns true if variable 1 is greater than variable 2
> =(greater than
Higher than or equal to variable1 >= variable2 If the variable 1 is greater than or
, is equal to the variable 2, returns true.
<(less than
) variable1 < variable2 Returns if variable 1 is less than variable 2
True.
< =(less than
Be equal to or equal to variable1 <= variable2 Return true if variable 1 is less than or equal to variable 2.

Arithmetic operator

The operator example explain
+(addition) print(variable1 + variable2) Print variables 1 and
The addition of the variable 2.
-(subtraction) print(variable1 - variable2) Print the variable 1 minus
The result of variable 2.
*(multiplication) print(variable1 * variable2) Print the multiplication of variables 1 and 2.
/(division) print(variable1 / variable2) print
Variable 1 over variable 2
%(remainder) print(variable1 % variable2) Print variables 1 and
The remainder of variable 2

Control flow and conditions

Programming involves making complex decisions. We need to learn how to make decisions in Swift. Suppose we are trying to determine whether a number is even or odd. To do this, we need to check whether a given number can be divided by 2 without leaving a remainder.

In Swift, we use %, find the remainder and determine if it equals zero. Let’s say we have a var num = 15. Let’s write conditions to find out whether this number is even or odd.

The remainder structure

To find the remainder, follow the structure below.

Keyword (conditions) {
    // code for execution here
}

Copy the code

The keyword we will use is if. The condition will be Num % 2 == 0 and the code executed is print read Given number is an even number.

var num = 5
if (num%2 == 0) {
print("Given number is an even number")
}

Copy the code

Suppose we also want to notify the user when the number is not even. This part is easy! We can do it in code in every statement. For each if statement, we can write an else statement.

If/elseSentence structure

Our code will use the following structure.

if (conditions) {
    // Run the code inside if block
} else {
    // Run the code inside else block
}

Copy the code

You will see the structure and conditions in the following code block.

var num = 5
if (num%2 == 0) {
print("Given number is a even number")
} else {
print("Given number is a odd number")
}

Copy the code

Because of the value of NUM, either the if statement will work or the else statement will work. You can only satisfy one at a time.

Let’s expand on that. Let’s say we want to ignore all negative numbers. We will run an if/else statement to exclude numbers below zero.

To solve this problem, follow the following structure.

if (conditions) {
    // Run the code inside if block
} else if(conditions) {
    // Run the code inside else if block
} else {
    // Run the code inside else block
}


if (num < 0) {
    print("Given number is a negative number")
} 
else if (num%2 == 0) {
    print("Given number is an even number")
} 
else {
    print("Given number is an odd number")
}

Copy the code

Simple, right?

Now, suppose you want to show whether a number is positive or negative and whether the number is even or odd.

var num = 3 if (num == 0) { print("Given number is a zero") } else if (num < 0) { print("Given number is a negative number") } else { print("Given number is a positive number") } if (num%2 == 0) { print("Given number is an even number")  } else { print("Given number is an odd number") }Copy the code

You will receive the following output.

Given number is a positive number
Given number is an odd number

Copy the code

cycle

Imagine you want to write down every number from 0 to 100. This should be fairly easy, right? What if I told you to write down every number from zero to a thousand? Or from zero to 10,000? It will be difficult, boring and time-consuming.

In this case, computer programming comes in. You can program a computer to do a certain task in a certain amount of time, and you can tell it what to do. We will ask the computer to use a loop in our Swift Playground to write 0 to 100.

In a loop, we can provide continuous tasks and interrupt conditions. In Swift, several loops are available, including for-in, while, and repeat-while.

We’ll go through each loop and use each loop to perform the same task. Let’s say we need to count from 0 to 100.

for-instructure

Use the following layout to build a for-in loop.

keyword counterVariable in lowerLimit .. upperLimit {
// code for execution
}

Copy the code

We’ll use for as the keyword and count index as the counterVariable. LowerLimit is the smallest number we start counting, and upperLimit is the highest number we stop counting.

for count in 1... 100 { print(count) // for printing }Copy the code

Now, let’s use the while loop to perform the same task.

whileLoop structure

Set your while loop in the following order.

keyword condition {
// code for execution
}

Copy the code

The keyword we’ll use is while, and the condition we’ll specify is to stop the loop. In our case, we stopped when the count was equal to 100.

var count = 1
while (count <= 100) {
    print(count) // for printing
    count = count + 1 // for increment value
}

Copy the code

If we didn’t increment the value using count = count + 1, the while loop would continue indefinitely, eventually crashing the program. A slow computer can be hard to reset, so before running your while loop, be sure to read the code again to make sure you include a stop point.

repeat-whilestructure

In the while loop above, we first check the condition and then run the code inside. Consider the same code example you saw above, with 101 as input.

var count = 101
while (count <= 100) {
    print(count) // for printing
    count = count + 1 // for increment value
}

Copy the code

In this case, we will not receive any output because the condition is not met.

Let’s try our example again with repeat-while. The repeat-while loop first performs the task and then checks the condition, essentially running in the reverse order of the while loop.

var count = 101
repeat {
    print(count)
    count = count + 1
}
while (count <= 100) 

Copy the code

The output of the repeat-while code is 101.

Hopefully by now you’re familiar with the Swift loop!

Here’s a problem for you to solve: Find all the even numbers between 1 and 100 and print them in the console. Your finished code will look like the following code block.

for count in 1... 100 { if (count%2 == 0) { print(count) } }Copy the code

Try yourself using while and repeat-while, performing the same task.

function

To understand functions, we’ll revisit loops. Loops allow us to write programs that repeat the same task over and over again.

A function allows us to reuse a large chunk of code when needed. We can write either an if/else statement or a loop inside a function. In general, a function takes some arguments and uses them to return a result.

Let’s run an example. With a function, we receive the result of the sum of two numbers, and we can change the input value at will. Note that a function only works if you call it, and you can call it as often as you want.

The function structure

We will use the following structure to complete this example.

Keyword functionName (parameters: parameters type) → returnType {// block of code here}Copy the code

Below, you’ll find the complete code, including keywords, function names, parameters, and return types.

func sumOfTwo(num1: Int, num2: Int) -> Int { 
  return num1 + num2
} 
var total = sumOfTwo(num1: 10, num2: 20) 
print(total)

Copy the code

The following code block shows the flexibility of the function. Note that each row contains a different numeric value.

func sumOfTwo(num1: Int, num2: Int) -> Int {
    return num1 + num2
}

var firstFunc = sumOfTwo(num1: 10, num2: 20)
print(firstFunc)

var secondFunc = sumOfTwo(num1: 5, num2: 7)
print(secondFunc)

var thirdFunc = sumOfTwo(num1: 12, num2: 51)
print(thirdFunc)

Copy the code

We can call this function again and again with new values and get new results each time!

However, we can simplify the code a lot. If we just print the results, we can improve by shortening the code.

func sumOfTwo(num1: Int, num2: Int) -> Void {
    print(num1 + num2)
}

sumOfTwo(num1: 10, num2: 20)
sumOfTwo(num1: 5, num2: 7)
sumOfTwo(num1: 12, num2: 51)

Copy the code

The code used here will give us the same result as the code written above. We can print it directly from the function because we don’t use the value anywhere else.

You may have noticed that we’re using Void instead of Int, instead of returnType. Void means we don’t return anything, we just do what’s inside. You can do the same by running the following code.

func emptyReturn() {}
func emptyReturn() -> Void {}
func emptyReturn() -> () {}

Copy the code

You can also write a function that doesn’t take any arguments.

func goodMorning() {
    print("Good morning")
}

goodMorning()

Copy the code

See, we’re writing a log that doesn’t pass any values.

Let’s use what we’ve learned to try a hard example! Let’s say we’re building a mini calculator using a function that can add two numbers and subtract two numbers.

func sumOfTwo(num1: Int, num2: Int) -> Int {
    return num1 + num2
}

func substractOfTwo(num1: Int, num2: Int) -> Int {
    return num1 - num2
}

func miniCalculator(num1:Int, num2: Int, work: String) {
    if (work == "+") {
        print(sumOfTwo(num1: num1, num2: num2))
    }
    else if (work == "-") {
       print(substractOfTwo(num1: num1, num2: num2))
    } else {
        print("This operator function is not available yet.")
    }
}

miniCalculator(num1: 12, num2: 21, work: "+")
miniCalculator(num1: 12, num2: 5, work: "-")

Copy the code

The final task is to print all the even and odd numbers on a given array using the following function.

func oddOrEven(lowerLimit:Int, upperLimit: Int) { for index in lowerLimit... upperLimit { if(index%2 == 0){ print("\(index) is an even number") } else { print("\(index) is an odd number") } } } oddOrEven(lowerLimit: 1, upperLimit: 100)Copy the code

There are many different ways to write this code, but I chose to keep it simple.

conclusion

By now, you should have a clear idea of how the Swift programming language works. If you get the basics right, you can write more complex code in Swift.

Remember this is a marathon, not a sprint. Improving your coding skills requires you to practice every day. Be sure to check out the official Swift documentation to learn more about Swift.

Mastering Swift Basics first appeared on the LogRocket blog.