The Fundamental Swift Beginner Tutorial - Let’s get Started
Learning Swift programming especially when one does not carry experience before, then this Swift beginner tutorial is just RIGHT for you!
This swift programming tutorial will narrate down steps for how to read and write Swift code alongside complete swift coding examples and ultimately can become a Swift player.
Additionally, I have compiled a Swift cheat sheet for beginners that one can download and consist of the most common syntax that one will learn here.
The resourceful supplementary course of the event is Apple’s own Swift programming tutorial guide which is made up of in-depth technical documentation of the Swift apple tutorial.
Table of contents:
- Xcode setup
- Variables and Constants
- Data Types
- Math Operators
- If Statement
- Switch Statement
- For-In Loop
- While Loop
- Functions Point 1
- Functions Point 2
- Classes
- Subclasses
- UIkit
- Initializers
- More Initializers
- Optionals
- Properties
- Arrays
- Dictionaries
Let’s take a deep dive at the fundamental swift beginner tutorial as follows:
Xcode setup
In order to get started with making iOS applications, one needs to download a program known as Xcode from the official Mac App store; here, the tutorial Xcode swift is also called an integrated ios development environment or IDE in general.
Additionally, an IDE is a simple program that provides the necessary tools to write code in software, and Xcode assists in running and testing the Swift code on the computer.
High time to get started with a new Playground:
Post you have Xcode installed and launched successfully, one should follow the lines of welcoming dialogue:
And if you do not really get this ‘welcome dialogue’ then it’s time one needs to go up to the ‘File’ menu and select ‘New’ and follow ‘Playground’.
Do click on ‘Get started with a playground’ and the dialogue that pop-up allows one to choose the type of playground one needs to create. One has to select ‘Black’ under ‘iOS’ for this particular purpose.
The most advantageous thing is, that one can save a playground anywhere they want while making sure to remember where to save for easy access; and in my eye-sight desktop is the best foot forward.
Now, the most essential of the playground is to focus on the following:
- Code Editor: Over here, one will be typing Swift coding examples.
- Line Number: This line number will aid in referring to different lines of code.
Pre-Syntax to follow to go to XCode >> Preferences >> Text editing >> Line Numbers and one can turn those line numbers on or off.
Hence, one will also notice while hovering over the different line items, clicking on the play icon executes the code highlighted in blue on the left.
For instance, if one is hovering over line 2 below and can click play, Xcode will only run the first line of code, and if one hovers over the line then Xcode will run and include the point. And the status bar tells you the current status of the playground, and Xcode is ready to accept the code and run it.
Additionally, it allows hiding or simply showing the debug and/or console area and the place which is being tasted on Swift code.
And Execute playground, will simply run all the code in the playground. Whilst holding down the play button proffers two options, ‘Automatically Run’ and ‘Manually Run’
‘Manually Run’ mode is where one needs to either click this play button or the blue icon in order to run the code. And the automatic mode could be quite a cradle at times, and Xcode often wouldn’t update the results when this is constantly running in the background.
One can hold down the play button to change it to ‘Manually Run’ when the status bar says ‘Ready’ which will be able to click and run code again.
Variables and Constants
While one is doing coding, have to have this mindset of giving the computer instructions on how to process data, and one was to build a stock portfolio application, and for instance, one should have to write code to inform the computer/desktop/PC to manipulate the prices and initiate up with the percentage lost or percentage gained with time. Post this, one will have to write code to instruct the desktop/laptop/PC on how to display the user in a table format.
On the contrary. One needs to build a photo application such as Instagram, and have to write code to inform the computer to grab the images to display those to users. On top of this, if the user tries to upload a photo to their account, one will have a code explaining how to take the image data from each user’s phone and upload them to the file server to make an entry in the database.
Additionally, one is always working with data while building an application, and this lesson represents some simple pieces of data to you,
The above-mentioned snapshot is a look of a background thing and has different types of data, and data numbers like 123, and the decimal like 0.7 on the lines of 3 and 4, and one can even have text data as outcome such as “Hello” with a double quote.
Swift variables
As your computer/desktop/PC stores data in its memory to keep a track of where the data is and what that data is. In order to work with data, one needs a way to refer to the programs, and that’s where variables come in to assist keep track of data within an application.
It’s high time to learn how to create or declare a new variable to track a piece of data in memory, first type the keyword VAR, followed by a space and your variable’s name; one can name anything but the name should simply describe the data the variable will indulge.
One should follow a variable name, add an equal sign, and post the piece of data one needs to keep track of, as we named the variable “firstname”, we have to give it a piece of text data namely the word “Jerry”.
Note to make here, the single equal sign lets us assign a piece of data to where the ‘Firstname’ variable, And a complete example of the variable declaration is given below;
Var firstname = “Jerry”
Initially, let us use ‘firstname’ by printing “Jerry” to the console and we will perform this with the print() command and the outcome to the console whatever data you put in the middle of its parenthesis.
Hence, it looks like variables are quite flexible as if they can store whatever data value we want, and one can not assign data of a different type from what variable originally had,
Swift Constants
Post variable declaration, and assigning values to them, it’s time to look at similar constructs used to store data called Constants.
Let lastName = “Eric”
Here we need to notice that the code above looks quite similar to variable declaration, and the only difference is one needs to use the ‘let’ keyword instead of ‘var’, and the difference between a constant and a variable is that one can not reassign a different piece of data to that constant after declaring it successfully. Even if you try to do it, Xcode will throw an error.
Make a note here, that the example value is different, however, performs the same function.
This error in Xcode informs me that I can’t assign something else to the constant ‘lastName’ because it was already assigned the value of ‘Eric’.
At this very moment, it seems that variables are much more flexible than constants, and despite this, it’s preferable in some cases to use constants over variables; and in order to keep track of data, one does not intend to change later.
While having the Swift journey Swift coding example, one will build a sense of when to use variables versus constants, and if the program uses a variable that never changes its data, Xcode will suggest changing the variable into constants instead.
What are the best practices for Naming Constants and Variable:
Like we all knew that variable names should be descriptive enough so one knows what kind of data they hold, and are just a fine balance to upkeep when it comes to the length of names.
Few things to keep in check such as
- Variables and constants are used to keep track of data in the application
- High time to use the ‘var’ and ‘let’ keywords to declare new variables and constants
- One has to use the equal sign to assign data to a variable or constants
- Mandatory to use the camel case as a best practice for naming variables and constants
- And constants are like variables, but one can not reassign data to them after the initial assignment.
Data Types
Data types are data in applications and they can be as simple as text or numbers or as complex as photo data or employee records in a company database.
Over here, we will narrow down different data types in Swift. To begin with, let us dive deeper ar a line of code from the last chapter,
Var str = “Hello, Beautiful”
Above here, we have declared a variable called ‘str’ and assigned a piece of string or text data to it for better recognition, and as mentioned earlier one can not change the kind of data variable stores as shown in the following line:
str =20,
Below are the most common Data Types in Swift:
- String: Just a text data, and it basically refers to having a string of characters: var aString = “This is a string”
- Int: a short for “integer”, this type simply represents whole numbers positive and negative
var myInt = 110
var itemInStock = -25
- Float and Double: Here these two decimals numbers and the difference is that doubles have more precision than Floats, hence, they can store large decimal numbers.
let pi = 3.151591119
- Boolean: Booleans simply either ‘true’ or ‘false’ and they are perfect for when there are only two options.
var isTvOn = true
Whereas, the most common data types will work for a while.
Ways to Specify Data Types for a variable or Constant:
Now, it’s time that we learned we need the ‘var’ keyword to declare such new variables. Or ‘let’ keyword for new constants as follows;
var fistName = “Tom”
let lastName = “Smith”
Also, when are you declaring a variable or a constant the fact is an optional part of the declaration we left here, and after the variable or constant name one can add a colon and the type of data one is expecting this variable to contain to:
var firstName: String = “Tom”
Although, explicitly telling Swift examples code firstName will only store String or text data. Now here is a quick example of Data Types as follows at time of declaring variables:
- String: var str: String = “Tom”
- Int: var anInteger: Int = 100
- Float: var aFloat: Float = 0.2
- Double: var aDobule: Double = 0.3
- Boolean: var aBool: Bool = true
Are you interested in a quick recap:
- String, Int, Float/Double, and Boolean are one of the most common data types that will work with in Swift
- One can specify a data type while declaring a variable or constant, and leaving it off will eventually give a variable or constant the data type of the first piece at the time of assigning it.
Swift Math Operators
Swift Math operators chapter, we will take a closer look at some basic math operations that one can use with constants, variables, and equations in general; Whereas, the basic math operations consist: of addition, subtraction, multiplication, and division for easiness.
One can also chain them together something like this:
print(a*c*b)
Despite the Swift math operators, one can use the power function for exponentials, as demonstrated and functions accept two numbers, either doubles or ints, and of course the base and the exponent to raise the base to; as
pow(2,3)
One another common function of the Math operator is sqrt(), e.g. sqrt(9) would display the outcome as 3. And another operator is with ceiling or ceil() that rounds any number up to the next whole number and as the example shows, it rounds 5.5 to 6 and gives the whole number.
On another side, there is floor() that rounds any number down to the next whole number, as floor(5.5) down to 5 and the whole number rounded down to themselves with ease.
Incrementing and decrementing numbers are key:
Let us jot down a way to represent an increment a variable by one and in this case the variable ‘a’, and add 1 to it, and reassign it back to ‘a’ and as if we run the code in a playground and the equivalent shorthand way to writing the same thing is to use += instead:
a+= 1
And one can shorthand way of decrementing numbers as represented below:
a-= 1
The above-mentioned also works with multiplication (*=) and division (/=); and this shorthand exists because it tends to modify variables via simple Swift math operations often while expressing the logic or writing algorithms in Swift coding examples.
If Statement
So far we have arrived at a stage of understanding the variables, constants, and data types; now we will going to talk about a staple construct in all programming languages in this form or another: the If statement, and will start with this piece of code:
let b=20
print (“b is less than 20”)
Syntax of If the statement is,
if condition {
\\some code
}
Here we know ‘’if statement’ starts with the ‘if’ keyword following with the condition we are intending to test/ verify and with braces. Any of the statements or codes inside those braces will execute only conditions equate to true. And if the condition is false, the code in those braces will not run; here is a quick example of it;
Let b=20
If b<20 {
print(“a is less than 10”)
}
Coinciding the above-mentioned example, as we have assigned the value of b as 20, and the if condition will check if the statement is true but here it seems false, then the print condition will not print anything.
Else If condition
Like we know the standard if statement could be useful in certain situations, and if many cases have multiple conditions we need to testify, and situations like this will be using one another feature of the if statement we called as ‘else if’ clause and here is the syntax:
if condition1 {
//code/condition
} else if condition2 {
//code/condition
}
To better use this statement, we lend on the analogy of imagining standing in the middle of crossroads with two paths, one going left and one going right, and can only go down one path; whereas the if statement works similarly evaluates the conditions from the top to bottom and the moment we understand to finds a true condition,
let a = 20
if a<=30 {
print (“a is less than or equal to 30”)
} else if a<25 {
print (“a is greater than 25”)
}
While evaluating the condition we noticed the value of a is assigned as 20, and if considering the if and else statement, the outcome will be displayed as a is less than or equal to 30’.
Stacking Else IF clauses
This is much more flexible than the cool feature and here is the syntax:
If condition1 {
//code structure
} else if condition2 {
//some code
} else if condition3 {
//code structure
} else if condition4 {
//code structure
} else if condition5 {
//code structure
}
Else clause, and chaining conditions
Now, that we are aware of all the basics of the if statement it has been quite simplistic so far, and we build more sophisticated conditions to identify underlying facts;
Here is a quick recap of if statement clauses and here we go;
- Utilizing if statements to conditionally implement code
- Adding alternative conditions with the ‘else if’ clause
- Do use the ‘else’ clause as a final alternative will implement if no other condition is true or false
- And Conditions are checked from top to bottom
Switch Statement
After the If statement to run code under certain conditions, and after a while one will find themselves writing giant if statements with multiple branches, and consider via a Switch statement that we will go to understand here;
Syntax:
let chr = “a”
if chr == “a” {
print(“the character is a”)
} else if chr == “b”{
print(“the character is b”)
}
Now, if we want to compare ‘chr’ with every letter of the alphabet, you could use multiple else if clauses like the one and the result in a bigger if statement, which I don’t recommend. Here, we will use a Switch statement that becomes pretty easy to deal with.
Core Syntax
switch value-to-consider {
case value1:
//some code
case value2:
//some code
default:
// some code
}
This is time to discuss each of the parts of the above-mentioned core syntax:
- Let us initiate with the ‘switch’ keyword, followed by the expression or value that you could get via checking it; whereas in our first example, the constant ‘chr’ is followed by a set of brackets.
- Keeping braces inside, with preceding values one needs to compare with the expression via the ‘case’ keyword; after the value, especially a colon, then the code one needs to execute if the expression matches the case, followed by the next case, and so forth.
- And after the specific cases, one needs to add a ‘default’ case to run if the expression matches none of the other cases, Swift beginner tutorial cases have a default case.
Now, if we can replace the if statement from earlier with a switch statement, one can write out a whole switch statement for practice, but the Swift Xcode tutorial has an autocomplete feature that will sometimes autofill cases. Do type switch and choose the switch-switch statement, option and then navigate to the different fields to fill out utilizing the tab key.
For-In Loop
As we move ahead in the Swift for iOS tutorial, we learned how to build and/or write code that can be executed under certain conditions, and the lesson will simply cover a loop that allows us to repeat a block of code various times.
Later we know how they work/execute, it turns out one will need to use them all over the place, and Swift has its various kinds of loops, and initially, we all need to look at the for-in loop that repeats a block of code a specific number of times; and let say I would like to greet more than 5 people in a room, and one can print “hello” to the console five times like as following:
print(“hello”)
print(“hello”)
print(“hello”)
print(“hello”)
print(“hello”)
print(“hello”)
print(“hello”)
Although, a for-in loop can condense the syntax into just a few lines, and let us emphasize its syntax first:
Syntax as follows:
for counter in lower….upper {
//some code condition
}
Now, if we go over each part of this syntax as follows:
- As true to its name, the main keywords of those loops used are ‘for’ and ‘in’
- And if we start with the keyword ‘for’, followed by a variable name, one should not have to use ‘var’ over here, and just add some stand-alone name to act as a place-holder.
- Post the variable declaration, type the keyword ‘in’ and then specify a keep of range, and the syntax for a range is number1….number2, which represents all numbers between number1 and number2, as this range is inclusive.
- Later in this range, one should add out a set of brackets, and inside the braces is where one can put their code, and the loop will repeat for whatever range one has specifically mentioned.
Counter Variable is for each interaction of the for-in loop which has the value of ‘counter’ refers to which iteration the loop in, for e.g. ‘counter’ contains 1 in the first iteration of the loop, then ‘counter’ contains 2 in the second iteration and so forth to count on.
Yellow warning: Over here Xcode utilized a yellow warning to tell us that if we do not need to use a certain variable, then one does not have to specify a name for it.
Here is a quick recap for a ready reference:
- One can use a for-in loop to execute a block of code to set a number of times.
- One can simply specify how many times the mentioned loop runs with a range
- And each of the loops runs its code is called a loop interaction
- Additionally, loops have no recollection of variables from previous iterations
While Loop
As we learned about the for-in-loop, which repeats code for a set number of times, one needs to examine two kinds of the loop that allows one to repeat code indefinitely till a certain condition is met, and such kinds of loops are simply great when one does not know how many iterations one needs to get that job done.
While loop
Simply while loop imitates as if statement in multiple ways, and uses a condition to comprehensively whether to run your code or/and skips over its block of code entirely if the condition is initially false and here is the syntax:
while condition {
//some code
}
In order to prevent an infinite loop, one needs to write code that eventually made the condition such as;
var counter =5
while counter >0 {
print(“welcome”)
counter -=1
}
Repeat-While Loop
Also, the next indefinite loop will simply examine is the repeat-while loop, and here is the syntax below:
Repeat {
//code condition
} while condition
And the Syntax is similar to a while loop, however, our condition is now on the bottom that one will start with the ‘repeat’ keyword that will surround the code to repeat, and later one have the ‘while’ keyword and loop condition that concludes the repeat-while loop.
Additionally, one may wonder how to work on and decide on which loop to use among one’s and depending on that one is trying to accomplish; whilst code one should know to execute once and only conditionally can repeat afterward, and the code should run only while the such condition is true and one should use a while loop.
Here is a quick recap for ready reference:
- Over here, the while loop and the repeat while loop let one execute a block of code and loop it indefinitely until a condition is met or not
- Whereas, the while loop checks the conditions first even before executing the block of code, and the looping
- And later the repeat while loop executes the block of the code first, and later checks one’s condition to decide whether or not it should repeat for another iteration.
Functions Point 1
A function point 1 is a function that is a named block of code that one can execute on demand by simply calling the name; And functions aid one to organize code into smaller chunks for specific tasks, so one can simply run a specific function in order to execute a specific program.
Also, a function can also take in custom data to work with and making it simply work more versatile here is a syntax to rely on:
fun name() {
//some code structure
}
One can start defining the function with the ‘func’ keyword which can be followed via the function’s name and alongside variables the name can be anything as long as it sufficiently describes what the function can perform.
This is time to learn about input parameters that can add to make the function more flexible and now finally let us add a pair of curly braces to contain the code the function will run while we call the name.
What to define a basic function:
func addTwoNumbers() {
let a = 1
let b = 2
let c = a = b
print ©
}
A quick recap of the fresh-n-up chapter we demonstrated here:
- All such functions assist us in organizing our code into executable blocks
- On contrary, the ‘fun’ keyword defines a function, we could use the function name to call it
- The scope of a function in between is simply curly brackets.
- And variables and constants created that are in the function’s scope are only accessible in that function only.
Functions Point 2
Earlier, we learned the functions and how to call them with fun(); and one has only seen basic functions which print out things when one calls them off. And these kinds of functions are called “void” functions because these functions do not get us data back to us data back, and rewrite functions are returned data.
Return values:
This turns out common use-cases for functions to take some input in order to perform some task to return its results, and the first step to specifying our function actually returns something we name it:
In order to do so, one must need to add an extra part to the function syntax:
func name() -> DataType {
//code syntax
return someValue
}
Input Parameters:
Additionally, input parameters go in between the rounded parentheses as showcasing in below syntax:
func name(argumentLable parameter name: DataType) {
//code structure
}
In this, all input parameters go in between the rounded parentheses.
Here is the chapter recap for ready reference:
- Utilizing the ‘return’ keyword allows the function to return a value back to its caller.
- And parameters let us supply data into the function when one is calling it
Classes
Classes are like custom data types in Swift beginner tutorials that help in organizing the information and how functions group pieces of code together, classes group related pieces of information together.
Syntax:
class name {
//class properties
}
Over here, we jotted down tons of information so far, much more for classes, and believe this introduction will open a way to get more clarity on the fundamental part of organizing the information.
Subclasses
Subclassing is like we can even organize such classes by using what we simply call inheritance; which is also known as subclassing and inheritance allows us to create classes to build upon or extend other classes which have already been defined. This eventually saves a bunch of time and effort from defining classes to do similar things with ease.
One can simply save time via using subclassing to construct new classes based on already existing classes to improvise and/or customize them without having to redefine from scratch or level zero.
UIkit
UIKit is yet another Apple framework that indulges many classes for most of the common elements which most iOS applications share, be it for labels. Text file, buttons, and images in examples of Swift code.
And if we tried to build these components from scratch, creating an application would be time-consuming; UIKit with all these pre-built elements can be used in the application instead.
One can explore UIKit to access the documentation and to find a page on any UiKit element, and recommended, even more, is via the Swift Xcode tutorial and to access it from Windows > Developer Documentation to find UiKit near the top.
Initializers
Classes have functions that we call initializer methods to assist set up new objects only how one wants to ensure they are ready to use.
let myPerson = Person ()
print(myPerson.name)
And one of the exciting facts about initializer functions is we can have as many as we like to add ones with their own input parameters,
More Initializers
Revisiting initializers methods via considering designated as well as convenience initializers, and in order to start, let us dive into a variation on the ‘person’ class we’ve catered to in the past chapters.
Syntax:
class Person {
Var name = “None”
}
On the other hand, the one property, name, initialized to the string as ‘none’, and now we are going to learn all classes with default initializer takes no arguments to create a new ‘person’ object using Person().
Alongside allocating memory for such objects behind the scenes are necessary, an initializer method to make sure all the object’s properties are initialized.
Now let us know what works in action;
class Person {
var name = “None”
var netWorth:Int?
var gender:String!
}
Recap steps are as follows:
- Designed initializers are simply required, guaranteed where all class properties are initialized while creating new objects for easy access.
- Also, convenience initializers are optional and help build objects in specific ways one may find convenient in this chapter.
Optionals
Over here, we will cover optionals for a swift programming tutorial, as swift tutorial is an essential part to get better aka understandable examples of Swift codes.
Now the question is how do these optionals work?
At this point, it’s about assigning something into a variable or constants right away while declaring ‘em.
And tutorial Xcode swift won’t simply be like that since it wants to make sure such variables and constants keep track of some sort of data.
Checking those optional Types and optional binding to check if an optional variable and/or constant actually contains an object;
// Optional binding 1
if let actualPresent = present {
print(actualPresent.surprise()}
}
And this optional chaining is another technique one can use to work with optionals.
In a nutshell, one will use optional most of the time such as we covered and from a futuristic perspective, will emphasize more complex aspects of optionals. Now, even if the purpose of optionals is not cleared yet, i could say when we get to create apps together one will know they are and now are being utilized.
Properties
Property scope and when we declare a variable or constant inside a function, and one can not access it outside that function, and because each function has its own variable scope; and on a similar front, any properties inside a class are accessible via the class methods since they are at all such class levels.
Computer properties: one can make a bonus a computed property that, unlike variables store values and stores as a calculation to declare a computed property while specifying the name and data Type with its normal properties.
Arrays
Managing several pieces of data may prove to utilize just constants and variables; perhaps arrays can be much easier. Arrays are simply ordered collection data and only store one type of Data, such as how variables have just one data type, and now we exactly know how to get one from.
Dictionaries
Dictionaries are another collection type and are common, especially when using data from a remote database or a third-party API.
These are simply like special arrays that can be indexed by anything, and allow us to access data using numeric indexes and dictionaries to retrieve values using indexes of the other data Types.
Although, data is added to dictionaries in key-value pairs that must apply a corresponding key which one can use to access the value later on.
One can declare a dictionary as follow:
var myDictionary = [String:String]()
Bottom Line
We believe this fundamental swift beginner tutorial which is backed by descriptive syntax will aid in your journey to Swift proficiency!!!
Do not hesitate to share your valuable input for this Swift tutorial! As have catered essential points to put together.