hello welcome to learn swift programming
for beginners lesson one today we're
going to talk about variables you're
going to learn about what they are how
to declare them in swift code and
furthermore how to use them
alright so let's get started
for the rest of the lessons in this
series we're going to be working inside
this app called xcode xcode is the tool
that apple has provided for people to
build apps with
and inside xcode you're going to be able
to create your user interfaces you're
going to be able to write the code to
express the logic in your app you're
going to be able to test your app even
so that's why this is where we're going
to start in learning swift we're going
to be writing the swift code inside the
app that you're actually going to use to
build apps with in the future
so this is where you're going to get
xcode just go to your browser
go to
developer.apple.com
xcode or you can launch the mac app
store on your computer and search for
xcode there if you're on the web page
you can see that there's this big blue
download button up top
now ideally you want to make sure you're
using the latest version of xcode and
right now as of this recording it's 8
and you can check your version if you go
to xcode you can see it here in the
welcome screen and you can also go up
here to xcode about xcode and you can
see what the version is if you're a pc
user and you're running windows there
may be some additional work you need to
do before you can run xcode or you might
have to use an alternative solution to
build ios apps so check in the
description below for pc solutions
however if you are a pc user don't let
that discourage you
for me personally i lost about two to
three years of learning ios development
simply because i didn't have a mac and i
didn't want to get a mac but these days
there are alternative solutions you
don't actually have to buy a mac
computer although i eventually did and
now i haven't looked back so anyways now
that you have xcode and after you've
installed it it's a pretty large install
it's pretty big program so i might take
some time but after you have it
installed and you launch it you're going
to see this welcome screen you can see
here that when you want to create an app
for iphone ipad mac or whatever you're
going to go to create a new xcode
project and that's going to start a full
out
project for you to build an app in but
here we're going to start a new
playground because that's going to allow
us to type some code quickly it's going
to let us run that code and see the
results and we're not committing to
building in a project it's simply like a
sandbox or a playground as it's named
now if you don't see this welcome screen
what you can do is just go up to file
new and hit playground right there and
that's going to start a new playground
for you as well
or you can just hit this button get
started with the playground
so that's going to launch this dialogue
for you and i'm simply going to leave
the default name there platform should
be ios
and i'm going to save this on my desktop
okay so after your playground runs
you'll see up here it's doing a whole
bunch of stuff
launching simulator getting it ready and
when it's done all that it's going to
say ready you can already start typing
in code so there you go it says ready
but
when it doesn't say ready and it's doing
something then chances are whatever
you're typing here is not going to show
up on the right hand side okay we're
going to start with a quick tour of this
playground window here
so down on the left hand side i have a
bunch of line numbers now if you don't
have these and you want them they can be
useful at times especially when i'm
teaching and i need to refer to line
numbers you can go to xcode preferences
and you can go to text editing and you
can simply enable line numbers there now
this area right here is where we're
going to type our swift code and it's
already got a bunch of stuff for us
right here which we're going to go
through in a second on the right hand
side you're going to see a quick preview
of the results of what you typed there
now a lot of people have trouble with
getting output to show up on this right
hand side based on what they type here
well one of the things that you can
check is just in this status bar up here
make sure that it says ready
and as you're typing something let's say
i change something like that you're
going to see that it
for a brief second there there was a
little spinner because it's evaluating
your code here
um if you want it to show up just make
sure it says ready to process your next
command
and
you know you should see that output
there
alternatively there is a tray down here
which you may not notice because it's
hidden at first you can hit this button
to show the debug area or there's also
this little button here to hide the
different panels
okay but we don't need to see all of
that but this debug panel
may be useful uh when we start to
output things here this is called the
console area where we can use swift
commands to output things
this blue icon here
is to execute the code in your
playground so if you can't get things to
show up on the right here try
clicking this button to run your
playground
right now it's blue because you can see
there's a little drop down arrow there
if you click and hold it you can see
whether you want to switch it to
automatically run
and that's going to run the playground
whenever you type something
or you can set it to manually run and
you can see now it's grayed out so if i
type in some new code it's not actually
going to
change or display what i have on the
right hand side here unless i click the
play button to run it
so i would recommend to have it set to
automatically run so now that you know
the main areas of the playground let's
get into the meat of today's topic
variables and in fact what we have here
is a variable in swift a variable holds
some data now this data could be a value
it could be a reference to an object or
it can even point to a function which
are things that will get into the future
but for now we're going to say that
variables hold data now as you can see
from this example line of code a
variable has a couple of distinct parts
let's break it down variables need to be
declared before they can be used so this
var keyword is used to declare a new
variable
following the var keyword you have the
variable name in this case it's str
and really that's it you've declared
your new variable so it's got the var
keyword and it's got the variable name
now taking a look at the whole line what
we have on the right hand side there
that's some data we did say that
variables hold data right and that equal
sign in between the variable name and
the piece of data well that's an
assignment operator so what we're doing
in this line of code is we're declaring
a variable called str and then we're
assigning that piece of data to that
variable
so now jumping back into the playground
let's see the effect of that i can say
something like print which is a keyword
that is going to print something to that
console area down below so if i say
print and then in the parentheses i put
str you can see that it's printed that
hello player s rough
line down there
on the right hand side
we can see a quick preview of that and
notice that there's a slash n here and
that is basically um just denoting that
there's a new line associated with that
print statement because
uh the next time i print something it's
going to be printed on the next line so
you don't see that here because a new
line is just
a carriage return or a white space you
can't really see it but in here in this
preview it's visualized as that slash n
which is just a new line
so let's take a look at a couple of
different pieces of data that we can
store into variables so i'm going to
declare
another variable here called a
and i'm going to assign
a number into it so just var one
and i'm going to declare another one
called b
which i'm going to also assign one
and i want to show you that you can
perform operations between the variables
or on the variables
so for example i can say print
a
plus b
and you can see here that the result in
the console here is 2.
now notice that when i'm using the
variables in
an equation or an operation like this i
don't need to use the keyword var
because that's only for declaring
variables right so this little part is
declaring the variable
but when you use them afterwards you
just need to refer to them by name
so let's try some other things print a
minus b
and print
a
times b
okay so variables hold data and you can
perform operations on variables
now you can change the data that the
variable is holding so i can say
something like a equals 2 now
right in fact actually let's not do it
down here let's do it here after we've
assigned one into a let's say a equals
two
and as a result you can see all of these
operations have changed because a is now
two so a plus b
is three
a minus b
is one and so on because a is now two
now when you assign something into a a
different piece of data it replaces what
it was holding on to before so a is no
longer one
it is now two but notice how when we
assign a new piece of data into a we
don't have to write var again
that would cause an error because we've
already
declared that variable up here and
memory in the system has been allocated
to it and so we don't need to redeclare
it all we need to do is assign new data
into a like that now if you're playing
around in the playground yourself you
may notice something like what if you
try to assign
something into str
like
one
well you're going to get an error and
that's because of something called data
types which we're going to learn about
in the next lesson but for now
just know that for str because we've
assigned some text into it up there
if we want to reassign some data into it
again it has to be text as well
so that would be valid
furthermore
you can also assign
a variable as another variable so i can
say
a equals b down here
and in that case a would now equal one
again
well
it was one to begin with so let's say i
did that so if a was two
and then i said a equals b then now they
would both be one
now before we move on a quick note on
naming variables here we have a variable
str and i've named some variables a and
b
so normally you wouldn't name variables
like a and b because they're not
descriptive of the data that they hold
so if you're going to be using variables
just like this in an operation wouldn't
it be easier if you knew what a
represented and what b represented well
you can declare your variables using any
sorts of names that you'd want but you
can't put some special characters and
you can't put spaces in your variable
name however the common practice is to
use a form of camel case where the first
letter is lowercase so let me show you
what i mean so i can say var and if i
want to describe my variable if it
represents
let's say the number of apples that i
have i would say something like
my
number of apples
like that and you can see that each new
letter
of each word is capitalized except the
first one
now you don't want to get too crazy with
the length of the variable name as well
and you don't want to go too short so
short that it doesn't actually mean
anything so there's no right or wrong
answer or hard limits it's based on you
know your own preference and it's more
important if you're working in a team
with other people that you agree on a
certain coding style because you're both
going to be working on the same code
okay so one more thing i want to talk
about are constants so they are like
variables except that once you assign
something to them you can't reassign
data into them so that's really the only
difference that and also how they're
declared so with variables you use the
keyword var but with constants you use
the keyword let so i can say let c
equals 10
and then down here if i try to reassign
something into c like that
xcode is not going to like that and it's
going to throw an error and it's going
to tell you with this red dot down here
and if you click it it's going to say
cannot assign value to c because it's a
let constant now it gives you this
little bubble here which you can click
and
smartly it's going to change let to var
because it senses that you want to
reassign data into it so you might ask
why would i ever want to use a constant
if it's more limited in its
functionality right if i declare
everything as variables then i have all
the flexibility i'd want
well there are a couple of reasons why
you'd want to use constants when it
makes sense for one thing it helps the
computer work a little more efficiently
because it knows exactly what that
constant will be and that's not going to
change but more importantly it's that
for you as a coder you know that that
constant isn't going to change because
when you're building your app you're
going to have a lot of variables
and when you have some sort of
issue in your app and you don't know why
it's happening and you're tracking down
your code you're tracing it line by line
and you're trying to see if maybe at
some point you've accidentally assigned
something to a variable and that's
throwing off all your calculations or
all of your logic it's going to be a
nightmare to try to solve and untangle
so if something you know it isn't going
to change you can assign it to a
constant and then when you're looking
through your code you can be sure that
the issue doesn't lie with that constant
because you know it can't change okay so
that's it for this lesson on variables i
hope you're practicing on your own
computer with xcode and check below this
video for a link to the cheat sheet and
the notes
hello welcome to learn swift for
beginners lesson two in this lesson
we're going to talk about data types
did you know in the previous lesson that
you're already working with different
data types well let me point it out to
you
let me open up the playground that we
were working with in the previous lesson
do you remember how we were trying to
reassign data into the variable str
and i was assigning something like
a number into str and i told you that
you couldn't do that in fact xcode tells
you that you can't do that right here
so if we take this little console area
and we scroll the scroll bar all the way
up to the top the error message actually
tells you what's going on cannot assign
value of type int to type string
well what's an int and what's a string
well those are two examples of data
types just as the name implies
a data type is a classification or
a type of data
for example a string is a data type that
describes pieces of text
an int short for integer is a data type
for whole numbers negative or positive
however there are many more data types
than just these two
other types of data that you'll commonly
be working with are float for floating
point numbers or decimal numbers and
then there's double
for decimal numbers where the decimal
portion may be very large
and then there's boolean which
represents true or false or in other
words yes or no
these are some of the more common data
types that you'll be using
and the reason why there are different
types of data is because the system
stores different types of data
differently and so when we go back to
the playground and we take a look at
this variable that we declared here str
and it stores a
string
the system has allocated this variable
to store this piece of
text or string in other words and when
you try to assign an int into that same
variable
it doesn't allow you to do that because
strings and ins are stored differently
now you might be wondering what
differentiates a variable that stores a
string like this str variable versus a
variable that stores a number or an int
like this variable a
well when you declare a variable
you learned in the previous lesson that
you use the keyword var and then the
name of the variable
well optionally you can also put beside
the variable name colon followed by the
data type
and if you declare your variable this
way you're basically telling the system
that this variable
can only store this type of data
and if you omit that part and you just
simply declare your variable with var
and then the variable name
then what it's going to do is as soon as
you assign a piece of data into that
variable it's going to take a look at
what type of data that is and assumes
that that variable stores that data type
so now going back into the playground
here it's as if we declared this st our
variable like this
right and these ones
are like this
now for instance if i declared this str
variable like this
then this line would be an error because
i'm trying to assign
a string
into a variable that is of type end
so it's not going to like that
now let's change this back to a string
for a second
and go back to this line where there's
an error now you understand why
this line is in red
because we can't assign an in into a
string variable well there are ways to
convert data from type to type
in some cases it makes sense like 29
here this in can be represented as a
piece of text simply like that
right but conversely
this hello playground line
right here i can't convert that to an
integer because it doesn't make sense
that this message could be represented
by a number
so for example just as a little preview
here if i wanted to convert this number
or this integer into a string
would create a new string and pass in
the number like that now i'm not going
to go into detail about why this works
or what this line is
because then you're going to have to
learn about classes and initializers and
stuff like that but for now in this
lesson i want you to understand that
there are different data types why there
are different data types and how that
comes into effect when you're declaring
your variables and working with your
variables and your data
now before we end this lesson off let me
just show you a couple of examples of
the other data types we talked about
so float could be something like that
a double usually also looks like this
and you're not going to have a really
large decimal point unless it's like a
result of a calculation that you're
doing
and let me show you
a boolean which is represented as bool
so you can set this to the keyword true
or false which is going to come in handy
for the next lesson that we're going to
do on if statements
oh and there is a mistake here because
i'm redeclaring c did you see that
in the previous lesson we talked about
how you can't redeclare a variable see
we declared var c up here but i forgot
that we had tried to declare a constant
with the same name down here
so this is going to have to be f
i'll show you some other types of
data conversions here
so i can say let's print out
let's change
c
which is a float into an int
and what's going to happen is that it
just drops the decimal portion of that
so if you did print
let's convert d
which is a double into an integer you
can see here that it just chops off the
0.9 and you get 13. now there is a
rounding function which we can try out
right now
like that and then inside the
parentheses you can put d
which is our double 13.9
and what you're going to get as soon as
it finishes processing is 14 like that
but notice that the result is also a
decimal number see it has a point zero
there
so what you can do is wrap the result of
that rounding inside
a pair of brackets like this
inside an int
and then you'll get 14 without the
decimal
okay so that does it for data types
hello welcome to learn swift for
beginners lesson three in this lesson
you're going to learn how to express
some simple decision making in your
swift code using if statements
all right let's get started
so for this one we're going to start a
brand new playground
all right so we've done this before
let's just call this one the
if playground and i'm going to store
this on my desktop
okay so we're talking about if
statements today
and this is really exciting because it
lets us finally start to make decisions
through code and express some sort of
logic so for example
if i have
let's declare a
constant here
so let
a equals 10 for example
and i wanted to print this statement
only if a
is
less than
let's say 11 which
it is right here
but
um okay
actually that is
that is not right let's say four
and this gives us a reason to use the if
statement right
okay so print only if a is less than 4
but a is 10 right so we shouldn't be
outputting this so what we can use here
is an if statement and what it allows us
to do is only execute some code
if a certain condition is true
so in this case we want to print this
only if a is less than 4
so we can write an if statement to
check if that's true or not before we
print that statement
so let me show you what that syntax
looks like and if you're not familiar
with programming terms syntax is simply
like the grammatical structure of the
language so it's basically the key words
to use and
how we go about declaring an if
statement or writing an if statement so
it all starts with the if keyword
following the if keyword we have the
condition in which we want to check and
following the condition we have a set of
curly brackets
now inside the curly brackets that's
where we put the code that we want to
run
if that condition is true
so that's your very basic if statement
now going back to our playground let's
write it out and print this only if a is
less than four
so we can do something like that if
a
and then we can use this operator less
than
4
and remember we need to surround the
piece of code that we want to execute if
the condition is true
using a pair of curly brackets like that
so you can put the curly bracket on the
same line or you can put it on a second
line it doesn't matter
but what you usually want to do is
indent the code
that is inside it just so it's easier to
read i usually like to put this curly
bracket in
the same line like that
okay so now you can see that in the
console there's nothing printed and also
to the right here it doesn't give you a
preview because this condition is false
a is not less than 4 because a is 10.
now what if we changed a to 1
and let the playground process okay now
it prints this statement and it previews
the statement see it's printed down here
so that's your very basic
if statement
now there are other cool things that you
can do with an if statement there is an
else if clause
so for example using the else if clause
you can check a second condition if the
first condition evaluates to false and
the syntax for that looks like that so
you have your if condition and then you
have your curly brackets and then you
use the keywords else if
and then you check another condition and
you have another set of curly brackets
so if you write it this way
you're basically checking condition
number one
you know is that true if it's false now
you're checking condition two
and if that actually evaluates to true
then you're running the code inside that
else if block
now keep in mind that it kind of goes
from top down and if the first condition
is actually true then it's going to run
that piece of code inside the first set
of curly brackets and it's just going to
ignore your else if statement
so let's take a look at that inside the
playground so here
i'm going to put else if
a is
less than
let's say
8.
then now i'm going to print
only if a is less than 8.
so now i'm going to change
oops not this i'm going to change a
back to 10 here
and you can see nothing gets printed
because
first it checks this condition if it's
false which it is
then it's going to check this condition
and it's also false so
nothing gets printed
now what if i changed a
to 7
if i change the a to 7 you can see that
it prints the second statement because
first it checks this condition
that's false so now it checks this
condition and that actually turned out
to be true
so it's going to run this line of code
here
however if a is 1
then it checks this first one and then
it prints this one and then it totally
ignores
all of the other else if conditions
now i said all of the other else if
conditions right
i say that because you can have as many
else if conditions as you want so you
can say if als is less than
10 and then you can you can continue
adding as many conditions as you want
but keep in mind that it checks from top
to bottom
and as soon as it finds a condition that
is true it's going to run that piece of
code and ignore all of the other
conditions
now finally there is a clause that you
can run
if all of the conditions are true kind
of like as a fail-safe or as a last
resort
and that is the else keyword so the way
you write this is using the else keyword
it's not else if it's just simply else
and there's no condition attached
because if all of the conditions above
it are false then it's going to run the
code inside of this else statement here
so going back to the playground let me
show you what that looks like
else
print
nothing was true
and now let me change a back to 10
here
so you can see that it prints nothing
was true because it's checking the
statement it's false this statement is
false
and sorry i mean conditions
and this condition is also false because
a is not less than 10 a is actually 10.
so this would actually evaluate to false
and finally it just
gets to this else clause and it's going
to print what's in here
okay so let me show you a couple of
other things that you can do with else
statements and let's
change these print statements to
something that is a lot more
recognizable or easy to read
let's do that branch one
branch two
and here
oops
branch three
okay
so
um first of all let me show you how to
do less than or equal to
now you see it prints branch three so
that's how you do less than or equal to
and likewise you can do greater than or
equal to
and you can see here it still prints
branch three now what if you wanted to
check if it was exactly 10
you wouldn't do that because remember
this equal sign is an assignment
operator so what you need to do to
compare
if
a is equal to 10
you use the double equal sign like that
you can see here it prints branch three
okay so why don't we introduce another
constant up here let's say b
and let's have that equal to 4.
i want to show you that your conditions
for your if statements and your
different branches can get pretty
complicated
and you can involve multiple pieces of
data
in your condition
so you can go if a is less than 4
if you want to check
b as well and you want to say
you know end
b is less than 4
that's how you would do it you would use
this double ampersand sign and now
you're checking two conditions
you're checking is a less than four and
b less than four and only if both of
those are true
are you going to get this branch here so
let's try that out so if i set b to 1
and a to 1
then both of these conditions here are
true
so it's going to print branch 1.
however if i set b to 10 right
it's going to just
see it hits this branch 2 now because a
is 1
which is less than 8 and it didn't print
branch 1 because
this was false right even though a is
one and this part is true
we have to have this part to be true as
well because where you're saying is a
less than four and b less than four and
b is ten right now however
you can also do or so you can say
is a less than 4
or b less than 4
and in this case either condition can be
true and that would cause it to go into
this branch so you can see now it is in
branch one
all right so uh let's say a is ten and b
is one
so
a
is not less than four
but b is
right because you're using this or
statement you're saying is a less than
four
or b less than four and if that's true
then we're coming into here
now furthermore if you wanted to involve
let's do a c
you can combine you know multiple
conditions like this you can put this
into
a pair of parentheses like this and you
can say you know end
c is equal to three
so you can see now that you're saying
okay
is
a less than four or b is less than four
and also is c equal to 3 then come into
branch 1.
now these brackets matter a lot because
what you're doing is you're saying that
this has to be true
and
this has to be true but for example if i
just shift the brackets a little bit
and i say something like
this
then that changes the meaning completely
because now i'm saying
is a less than 4 or
is this part true right so where your
brackets are matter a lot and it changes
the meaning of what you're checking did
you get that in this case i am checking
is this true or
is this true
but the other way around
i'm checking
is this true and is this true
right so the brackets matter
finally let me show you another operator
that we have here so here we have we're
checking is c
equal to three well what if we want to
ask is
c anything but three or is c not equal
to three
if we only care
about the case where c is not three we
can say something like this not equals
to three
and this is going to say
is c
not equal to three
so you can see here that c is three so
that's why it completely skips this
branch and
it ends up being a is equal to 10 and it
prints branch 3.
now you can use this not operator this
exclamation mark here on other things as
well so for example here i'm asking is a
equal to 10
right and i am
uh it's coming in here because a
actually is 10 and so it's printing
branch 3
but if i surround this
like that
let me put something else in here is a
equal to 10
and b
equals to 1
right that is true
so that's why i'm still getting branch
three
but if i put an exclamation mark here
like that it basically flips it around
so
this evaluates the true right a is a 10.
this evaluates to true
both
this whole condition evaluates to true
right
a
is a equal to 10 and b is equals to 1.
and then so we get true
but then we're adding this guy here it
flips that true to a false
so
that's why
this whole condition equates to false
okay so that does it for if statements i
hope you're trying this out on your own
computer in the playground because trust
me it's pointless to try to memorize all
of the keywords and the syntax for the
swift it's much better if you you know
only spend 30 minutes instead of trying
to memorize things spend 30 minutes in
the playground
just punching in different numbers like
that playing around with the different
conditions and expressions
and printing out a bunch of stuff in the
console in 30 minutes you'll remember
a lot more just by doing that than
trying to memorize you know how to
declare a variable or how to declare an
if statement so
you know if you can get a mac get xcode
open in a playground and then type this
code out for yourself and play around
with it it's going to do wonders
so thanks again for watching and if you
like this series so far please give the
video a thumbs up please subscribe it
really helps
hello welcome to the learn swift for
beginners series lesson four
in this lesson you're going to learn
about switch statements and like the if
statement it allows you to make
decisions with your code alright so
let's get started
let's start by creating a new playground
for this example
and i'm going to start labeling these
after the lessons here
and i should have done this sooner but i
want to point out that apple does have a
swift programming language guide
and in this guide it goes through all of
the syntax and the structure and the
different concepts of the swift
programming language it's what we're
doing in these videos and more in fact
so if you want something to read you can
go ahead and visit this website here
i'll have the link below the video
but one thing to note is that it may be
a little bit complicated for the
absolute beginner who doesn't have
programming background
but give it a try and it's a great
compliment to watch with this learn
swift series that you're watching
in fact as we're going through the
different concepts in these videos i'll
point out
in the guide where they are so for
example we're looking at the switch
statement today and that resides under
control flow and you can see here what
the basic syntax is for this switch
statement
okay so let's jump back into our
playground and we can do an example of a
switch statement so in here i'm going to
basically
do the same example or similar example
as the one in the guide
and
i'm going to introduce a new data type
called character and it's basically like
a string except that it's just a single
character like that
and with an if statement we can do
something like this if some character is
you know equals
a for example okay like we have right
here
print
is n
a
and this is going to be true and it's
going to print this out and then we're
going to have else if and we're going to
maybe check another condition if we
wanted to you know respond to different
cases depending on what letter this
variable is
right but you can use a switch statement
and it looks like this
so we start with the switch keyword then
you have the value which you're
considering in our case that value is in
the variable sum character
so that's what we would put in there
and then you open up a pair of curly
brackets
inside these curly brackets you have
different case labels so you would have
case if you wanted to consider the case
where the value is an a you would have
case a and then you have colon and you
would have something to do if it were
that case
perhaps this would be easier to
visualize if we take a look at the
playground so let's jump back to the
playground here
so let me say
switch statement
right on the value that we're
considering so that's some character
and you open up a pair of curly brackets
like that and then you have your case
labels so i have case you know if it's
an a
and if i want to do something for this
case right then you have a colon and in
here you would print let's say is an a
like that
and if there's another case right i
would have case
b for example
and i would say
is a b
and lastly if none of those cases are
true i would have a default case like
that
and i would say
print
some fallback
so in this switch statement
this case was true
right so it printed out the statement
and it doesn't do the rest and you can
have more lines of code in here than
just the print statement in all of our
examples you know i just wanted to show
that it's coming into here this branch
but you could execute more code in here
now the case where you know
character is a b
then we would come
into here and jump into here now if it's
not none of those cases we would have
default and it would print that
and of course you can have
a whole bunch of different case labels
it just doesn't have to be the two that
we have here the benefit of using a
switch statement is that rather than
using an if statement and having all of
these else if clauses
reading this is much more clean
and it's a lot easier to read as well
so what if you wanted let's say two
different cases to run the same piece of
code or the same block of code so for
example if i change this to say
is b
or
you know a c
is a b or c
i could do something like this with this
case label here i can do that comma and
then i can put
this other case there
so this saves me from having to have
another case c and then you know the
same
code i can put a comma here put the
other case here and have either one of
these cases use the same block of code
so now you can see that it comes into
this case here prince is a b or c
instead of coming into default
so why would you want to use a switch
statement over an if statement well if
there are a lot of different conditions
that you want to check on a certain
value rather than using an if statement
with a whole ton of else ifs you can use
this switch statement which is easier to
read and easier to understand
you're probably going to use the if
statement more than the switch statement
but it's still a handy tool to have in
your arsenal so i highly recommend that
you try this out
in your playground
so that's it for switch statements this
is a short one i hope you enjoyed it
please help this channel grow by
subscribing and hitting that thumbs up
button below the video
hello welcome to learn swift for
beginners lesson five in today's lesson
we're going to talk about loops
when you're writing your app there's
going to be many times you're going to
find yourself needing to repeat pieces
of code
for instance let's say you're showing
five things
in your app and you need to turn each of
them red
so a loop is going to allow you to just
write that single line of code to turn
something red and you can repeat it five
times for each of those five objects
and that's going to save you from having
to
write out that code five times
so
that's a very simplified example
but trust me you're going to use them a
lot so let's take a look at how to use
them
so there are three types of loops we're
going to cover today we're going to
start with the four in loop as you can
see in the swift programming guide here
so let's go ahead and start a new
playground in our xcode
and i'm just going to call this
the loop playground
and save it on my desktop
now a for in loop allows you to repeat a
piece of code a certain specified number
of times
if you have a list of data otherwise
known as an array which you're going to
learn about in an upcoming lesson you
can also use a for in loop to go through
each of those pieces of data in that
array and execute some sort of code on
it so this is perfect for the example we
mentioned in the intro about having five
objects or five items on the screen and
you need to turn each of them red for
example
so let's start with learning how to use
a foreign loop to
repeat a piece of code for a specified
number of times and when you guys learn
about arrays
i'll show you how to use a foreign loop
to go through each piece of data in that
array
so as you can see
true to its name the keywords to use
here are for and in
so you start with the keyword for and
next you have a variable name now you
don't have to declare this variable
using the var keyword like you've
learned in the previous lessons you can
simply have a name for this variable
because you're only going to refer to
this variable
within the for in loop
this variable that you specify here is
going to keep track of which iteration
of the loop is currently running
next up you have the keyword in
and then you have the lower range
followed by
dot dot and then the upper range and
that last part there after the in
keyword is the range which your for loop
is going to run in
and it's inclusive of those numbers so
for example if you have
1.5 it's actually going to run five
times
and then after that you open a set of
curly brackets and inside the set of
curly brackets that's where you're gonna
put the code that you want to repeat for
that number of times
so let's jump back to the playground and
let's do a quick demo on that for in
loop
so i have the four keyword here
and
for my variable i can specify something
like index
and then i would put in and let's use
that same example one to five and then i
open up a set of curly brackets and then
here i'm simply going to print
hello
and we're going to see this in the
console down here
it has printed it five times
now part of the reason why you specify a
variable name here called index
is because you want to use that
that number or this variable inside your
for loop here so for example i can
do something like this
where i can say
print index and you're going to see that
index changes
from 1 2 3 4 5 depending on
which iteration of the loop it is it
keeps track of
basically where we're at
in this range right here as we're
looping through it
but again what we've specified here as a
counter is only available inside this
scope here in between these curly
brackets i can't specify
you know printing index out here it's
not going to recognize it
okay so
we can't do that
and furthermore
if you don't need to use index inside
your for loop you can very simply place
an underscore there
so this is perfect for the example that
we had
initially
where we're just printing hello five
times we don't really need
a counter of any sort we don't need to
refer to index we don't care which
iteration it's currently at
one thing i want to mention which is
confusing often for beginners is this
idea of scope
here for example if i wanted to sum up
the numbers from one to five and i
wanted to print out the result after the
for loop
let's say i declare a variable up here
and i call it sum and i equate it to
zero and then i say something like sum
plus equals
and actually let's add this
index variable back here
and i go like this now you haven't seen
this plus equals
sign yet
but this operator basically
equates to something like this
it takes sum and it adds
the index so this is equivalent to
writing
this it's just kind of like a short form
okay so first of all
if i declare this variable called sum
inside my for loop inside these curly
brackets
well this variable is only available
within that scope within these two curly
brackets i can't go out here outside of
the for loop after it's run five times
and print out the result of sum
see you can see that it can't find this
variable even though i've declared it in
here
okay so why don't we move this print
statement into the for loop what would
you expect to happen in this case
well we get one two three four five
again
and why is it that
this sum isn't increasing why isn't it
continually adding index to it and
you know why aren't i getting the sum of
the numbers from 1 to 5 by the last
iteration of the loop well what's
happening is that
in the first iteration of the loop we're
declaring sum
equals to zero
and then we're adding index to sum which
is one and then we're printing some so
that's why we get one down here
in the second iteration of the loop what
we're doing is we're declaring sum again
we're setting it to zero
and we are adding
um this time the index is two and we're
adding two to zero right and then it's
going to print two so
that's why you can see the output 2
right there
well right now you might point out to me
hey chris i thought you said that you
can't really declare the same variable
you know in the first iteration of the
loop we're declaring var sum
right and then in the second iteration
of the loop we're re-declaring var sum
that's that's illegal that's not allowed
in fact
you might say that you know if i declare
var string again up here
it's going to throw an error right we
can't redeclare the same variable
because
we've declared this guy up here we can't
redeclare it using the var again
and i would say that's true except that
in each iteration in the loop it's
almost as if
it doesn't remember what happened in the
previous iteration there's no memory or
recollection of the previous iteration
so each iteration is kind of like a
clean slate and it's going to execute
this code right here
so just to say that again you're right
if you're saying that
i can't read a clear sum
right because if i tried to do that
right here
xcode would throw an error
however inside of a loop in this scope
right here
each iteration of the loop is like a
clean slate okay
now if i wanted to
actually find out the sum of the numbers
from one to five what i would actually
do is i would move this declaration
up here outside of the loop
and then what i would do
[Music]
this way
i could move this print statement
outside of the loop and what this four
in loop will do is simply loop from one
to five each time
adding index to the sum and now i'm
actually keeping track of the sum so you
can see that after five iterations of
the loop
adding the numbers from one to five into
sum which started out as zero
the result is 15 down here
and that's from this print statement
okay so i'm going to stop the lesson
there
while the syntax for the foreign loop is
actually pretty simple and and the
concept of repeating a piece of code for
a certain number of time is pretty
simple
i want to give you some breathing room
to digest what we talked about
in regards to the variable scope
so i would recommend that you try
declaring and creating this loop
on your own computer
try declaring the variables inside the
loop and outside the loop and see where
you can access them and use them and
where you cannot
it's really going to help and aid you in
your learning
hello welcome to learn swift for
beginners lesson six
in this video i'd like to introduce you
to two more types of loops and that is
the while loop and the repeat while loop
and these two loops lets you execute
some code until some condition is met so
that's different from the foreign loop
where it repeated a certain number of
times
okay let's do it
for this lesson we're going to create a
brand new playground and i'm just going
to call this the loop 2 playground
okay so let's cover the while loop first
take a look at this slide and let's go
through how to declare a while loop
so the keyword here is while
followed by that you have some sort of
condition and it's very similar to an if
statement so the while loop is going to
repeat that chunk of code
as long as the condition is true but as
soon as that condition becomes false
it's not going to repeat the code
anymore
after your condition you have a set of
curly brackets and inside of the curly
brackets that's where you have the code
that you want to repeat
so let's do a quick example back in our
playground
so i'm just going to declare a variable
here
i'm going to call this
let's say counter
and i am going to
set this counter to 10
and then i would like to
print hello
let's use
five instead so it doesn't print that
many times and i would like to print
hello as long as the counter is um
above zero let's say
so i would say something like while
counter is greater than zero
i would
i would do this print right here
however this is going to keep repeating
as you can see because
counter is always five so inside my
while loop i'm going to
computer is dying
okay
as you can see
it eventually
overflows and crashes
okay so what i'm doing here
is i am decrementing counter by one for
each iteration of the loop so as you saw
when i didn't have this line of code it
just kept printing hello
many many times because this condition
would always be
would always be false there was nothing
changing the counter variable from five
to zero
so i'm just going to warn you about that
if you're going to try this on your own
computer
you know if you have a slower computer
it might it might take a lot longer for
you to get out of that out of that loop
so you can write this statement first
make sure you have
a statement that is
decrementing your counter
so again this minus equals
is the equivalent of writing something
like this
counter equals counter minus one so
you're just taking whatever value
counter is you're minusing one and
you're setting that as a new value for
counter
as you can see here
it's what you would expect right you get
hello
five times
now let me point something out to you
right here
uh what if counter was
let's say negative five
you can see here that nothing gets
printed out because
this loop is going to see if this
condition
is false or true
before executing the code right so it
evaluates the condition
and then it decides whether or not it
should run this and repeat it
now the second type of loop the repeat
while loop is very similar to the while
loop except that
it checks the condition
after looping once so it checks the
condition down here let's take a look at
the syntax
so you start with the keyword repeat
and then you have a set of curly
brackets and inside the set of curly
brackets you place the code you want to
loop or repeat
and then after the ending curly bracket
you have a while keyword and you then
you have the condition
so the syntax of this repeat while loop
is very intuitive actually
it's basically saying repeat this piece
of code while this condition is true
okay so let's go back to the playground
and let's do an example here
so i am going to use the same example
okay let's print hello here
and we're going to have the same thing
counter equals counter minus 1
and we're going to say repeat
this chunk of code
while
counter is greater than zero so as you
can see it's pretty much the same loop
or same condition rather
right while counter is greater than zero
and that's the same thing i have up here
for this while loop
and
let's just print something else here so
we can differentiate it
and you can see the repeat while loop
actually prints it out
once and then it checks the condition
and it realizes oh i shouldn't repeat
this chunk of code because
this is false
right
whereas this while loop it checks the
condition first and it realizes this
condition is not true and it won't print
at all
so that's that's the main difference
between the two types of loops
both types of loops will repeat a chunk
of code until a certain condition is
false except that
the while loop checks first
and the repeat while loop checks the
condition after repeating once
hello welcome to learn swift for
beginners lesson seven in this lesson
you're going to learn about functions
how to use them what they are and this
is a critical part of the swift
programming language if you want to
build apps with it so let's get started
so here i've got a brand new xcode
playground where we're going to take a
look at what functions are and how to
use them how to define one how to call
one if you don't know how to start a new
playground just go back to lesson one of
this learn swift series okay let's start
with what a function is
at its very core a function simply
allows you to take a chunk of code give
it a function name and then whenever you
call that function name it's going to
execute that chunk of code
now that may seem simple but over the
course of the next couple of videos
you're going to see just how complex and
powerful functions can be functions are
really useful because it allows us to
break down and group our code into
smaller chunks
and we can organize them so that each
function or each chunk of code has a
specific task
and when you want to do that specific
task then you just call that function
so let's see how a function is defined
in swift code and then we'll jump into
some examples in our playground
so here we have the syntax for our basic
definition of a function now it can get
more complex than this because there are
a lot more features of functions that we
can use but we're going to explore those
in the next couple of videos for this
example here is your kind of basic
definition of a function you start with
the func keyword that's func
followed by the function name now this
function name is what you're going to
use to call the function
now right after the function name you
have two parentheses or two rounded
brackets
in this basic definition there is
nothing in between these two brackets no
spaces nothing in the next two videos
you're going to see what those brackets
are used for but for now
those brackets are just there as part of
the definition there's nothing in
between them
and then you're going to have a set of
curly brackets and as you would expect
in between the curly brackets you would
put the code for the function
so whenever you call the function name
that code in between those curly
brackets that code is going to be
executed
all right let's jump into the playground
and do some examples
i'm going to declare a function that is
going to
add two numbers together
and it's going to print the result to
the console so i'm going to start by
using the func keyword to declare a
function
and now i have to have a
function name
so i'm going to say
add
to numbers
that's my function name and you'll
notice that i'm using the same
camel case as i do for declaring
variables where i start with a lowercase
letter
of the first word and the following
words uses a capital letter then i have
my two rounded brackets like that
followed by
a set of curly brackets like that
and sometimes when you type in this
first
curly bracket or the opening bracket and
then you press enter xcode will
automatically add this ending curly
bracket for you
okay so in between the two curly
brackets i am going to
say let a equals one
let b equals two
and
i am going to
uh let's see equals
a plus
b
okay
and then finally we're going to print
the result of c
so you can see here that nothing
actually happens because this function
hasn't been called this code is sitting
here if we had written this code instead
of putting it into a function so let me
just delete this for now
like that
and this is what we've been doing so far
before we learned about functions we
would just declare these constants here
and then print c and you would see all
of the stuff in the output now i'm just
going to undo those two deletions
so to wrap this code inside of a
function now you can see nothing gets
output until i actually call the
function to execute this code right here
so how do we call a function so in order
to call a function you just have to
write the function name followed by the
two rounded brackets
now because we don't have anything
inside these two rounded brackets that's
all we have to do but as you're going to
learn in a couple of videos later
if we have something in between these
brackets the calling the function would
require a little more work but for this
basic function we can
invoke that function simply by writing
its name so add two numbers as you can
see here autocomplete even suggests it
so all i have to do is highlight that
line
press enter
and what happens now we get three output
into our console because by calling that
function it just ran the code down here
and i can call this again
as many times as i'd like and anywhere
i'd like one benefit is that if you need
to execute a chunk of code several times
this is a big savings rather than
writing this code out multiple times i
just put it inside a function give it a
name and now i can invoke that piece of
code whenever i call this function name
like this
so it helps you reuse code especially if
that chunk of code is going to be used
multiple times in your app you don't
want to write out the same chunk of code
multiple times in and around your app
because
it makes it really hard to debug for
example if you've got an issue with this
chunk of code and imagine if you had it
repeated several times in your app in
order to fix it you'd have to fix it in
every single one of those places but if
i have this chunk of code inside this
function
i would only have to troubleshoot and
debug this piece of code once here
and as soon as i change this let's say i
change this a to a two and let's say
that fixed my code and you can see here
wherever i call add two
numbers the code is updated so i only
need to update and change the code in
one place whereas if i wrote this chunk
of code out in multiple places in my app
i would have to change it in all of
those places
another benefit i mentioned is that it
lets you group this chunk of code that
performs a specific task into a function
that describes what that chunk of code
does so it helps you organize your code
so there is one more thing i want to
mention about functions and that is
about scope so same thing we learned
about inside of loops in terms of
defining variables applies here as well
so let me give you an example of what
i'm saying so let's say i get rid of
those two function calls and we simply
have this function here we have these
three constants c is obviously four
right and inside this function i'm
printing c so outside of my function
let's say i want to print c
well that is actually going to throw an
error that doesn't work why because the
constants and variables that you declare
inside a function can only be used in
the function in between these two curly
brackets
and likewise if i
declared another function
really quick quickly
so inside this function i also cannot
access the constants that i declared
here so if i declared
a constant
like that d equals one i can't say
you know uh
let e equals c minus d or something like
that
um inside this function it's not going
to recognize what c is right here
so let's get rid of this first okay so
there you can see the error it doesn't
know what c is because c is defined
inside add two numbers and so it only
recognizes
c within this scope a b and c in fact so
inside here inside this function i'm
free to declare a again because it only
applies within
these brackets like that
so i can have a minus d
and let's end off
by printing e
okay so the main takeaways for this
lesson right here
you've learned about what functions are
and why they're beneficial you've
learned how to define a simple function
you've learned how to call that function
so you can execute the code inside of
that function
and furthermore you learned about the
scope inside of a function
and just to remind you about that
it's that whatever you declare inside of
the curly brackets of a function is only
recognized and can be used inside of
those curly brackets
in the next video we're going to build
upon what we learned here in this lesson
and you're going to learn how to make
functions even more powerful
so thanks for watching if you liked the
video please give it a thumbs up it
helps this video get seen by more people
and subscribe for more
hello welcome to learn swift for
beginners lesson 8. in the previous
lesson you learned about functions how
to declare them and how to call them
in this lesson you're going to learn how
to use them in an even more powerful way
by having your functions accept data and
also return data to you when you call
them all right let's see how that's done
so here i have a fresh playground if you
forget how to open up a new playground
just go back to lesson one of this
series and you can see how now there's
one thing i want to mention before we
move on that i forgot to mention in the
previous video and that is that
sometimes i may accidentally say method
and when i say method i actually mean
function now i noticed that a lot of
other swift teachers also do this
and the reason for this is because
for many swift educators like myself
swift isn't our first programming
language and in many of the programming
languages out there there is some
concept of a function and sometimes
they're called functions sometimes
they're called methods and sometimes
even other things so
a lot of the educators out there when
they're teaching sometimes they're going
to slip up and they're going to say
method instead so i just want to put it
out there if you hear me say method
uh
just know that sometimes i use function
and method interchangeably
okay so we're going to start by
just redeclaring that function that we
had in the previous lesson and i want to
redeclare it just for extra practice for
you guys so i think it was something
like
um add to numbers
like this
and it was let a equals one
let b equals one and let's see equals a
plus b
and then we're going to print c just
like that
now in the previous lesson i mentioned
that functions are great for kind of
organizing your little bits of code into
um pieces of code that perform one task
so in this case
um this function would add the two
numbers together and then it would print
out that sum in the console but what if
i wanted the function to just add the
two numbers but don't print it out i
just want the result
so in fact functions have something
called a return value
and it's exactly how it sounds when you
execute the function it returns a value
to you
so let's take a look at what the syntax
is for specifying that a function
returns a value
so everything remains the same as our
basic function definition but after the
two rounded brackets you have an arrow
that arrow is just comprised of a hyphen
and a greater than sign and followed by
that you have the data type of the value
that this function should return
so now that you specified that this
function returns
a value you have to use the return
keyword inside of that function to
actually return a value of that same
data type that you specified
so now let's go back to our playground
and see how this applies to the function
that we have there
so let's say that for this function
i don't want to print out the sum
instead i wanted to return the sum to me
i would then erase this print statement
first of all
after the rounded brackets i would put
hyphen
greater than sign and then i would put
int
specifying that this function should
return an int data type
now xcode immediately throws an error
here because it notices that i
don't have the return keyword i'm not
returning
an integer value like i said i would so
what i would have to do actually to fix
this is use the return keyword and i'm
going to return c because that's the sum
of a and b
so now when i call
add two numbers like that it actually
returns c
now let me show you something here so
when i type that autocomplete it shows
you the return value right there it
tells me that add two numbers actually
returns an integer like that so what i
would do
essentially is i would probably
declare a constant
and let's call it sum and i would say
equals add two numbers what's happening
here is that i'm calling this function
add two numbers
and this function is returning
c
as in the sum of one plus one
and i'm assigning that value into this
constant called sum
so now if i print sum
like that
i would get 2.
so this constant sum it stores the
returned value from my function here
so one more thing i can do up here
instead of declaring this constant c
equals a plus b and then returning c i
could actually get rid of this constant
and i could just return a plus b like
that
and that would actually take a and b add
them together and then return it
so that's return values for functions
and this is really powerful because now
you can
write a function that does something and
returns the result to you
so your function is kind of like
a little worker or a piece of code that
does a specific task and then returns
you back the result
now there's another cool thing that you
can do with functions and that's called
parameters
see this function by itself add two
numbers
it's always just going to add one and
one together and return two to me
but what if i wanted this piece of code
to be reusable for any type of numbers i
want to specify which two numbers i want
to add together
so essentially what it is
is when i declare this function i can
specify in between these two rounded
brackets see i mentioned
in the previous video that we would use
this
in between these two rounded brackets we
can specify that this function needs
some input parameters in order to
execute so let's say that i'm going to
declare this function and say that when
you call this function you need to give
me two numbers
as inputs
now when i call the function here i
would have to specify two numbers in
between these rounded brackets
okay so before we actually do it let's
go take a look at what the syntax looks
like for declaring these
input parameters so this syntax right
here shows you what the function
definition would look like for a single
parameter now we're going to get to
multiple parameters but this is an
example of a single parameter
function declaration
so in between the two rounded brackets
you have an argument label
okay i'll explain to you in a second
what that is and then you have a
parameter name
followed by a colon
and then followed by the data type of
the parameter
you're accepting
now let's talk about the parameter name
colon data type part first
so obviously the colon data type part of
that
specifies what sort of parameter you're
going to be passing into the function
and the parameter name
is going to be the name of that
parameter you use within the function
so if i wanted to take that input and i
wanted to add it to something
and i wanted to reference that value
that was passed in i would use the
parameter name okay
inside the function
now the argument label for that
parameter is what is going to be shown
when you call that function
i know it's a little bit confusing right
now but let's jump into an example
so it makes more sense
all right so back to the playground here
let's
implement one parameter inside our add
to numbers function here so i'm not
going to use any descriptive names right
now because i want to show you how
the argument label and the parameter
name plays out so i'm going to say
add two numbers
argument label is
let's just say arg
and then the parameter i'm just going to
say para okay and then colon
int
so
this
function now accepts a parameter
that is type of int
and then xcode detects that now this
function call is incorrect
because we have no function that doesn't
accept parameters
so one cool thing you can do is just
erase that and go
add two numbers you can see that
autocomplete now recognizes that we have
a parameter so let's
double click that and you can see here
is the argument label
let's pass in the number here let's pass
in let's pass in 2
like that
so by specifying arg there as the
argument label for the parameter when i
call the function
i'm going to have this label here
if i wanted to use
this number that i passed in remember
you have to use the parameter name
that's for inside the function so
i would reference the value that's
passed in using the parameter name like
that so essentially what i would get
here
is because i'm passing in 2
and i'm referencing i'm setting a as
2 right that's our parameter that just
got passed in
it would be two plus one
so that's what is stored in the sum and
when i'm printing some
that's what i expect to get three
okay that is helpful but it's not
complete we want to be able to pass in
both numbers so that we can specify
which two numbers to add together let's
take a look at the syntax for multiple
parameters
so the syntax for multiple parameters is
very easy
in the parameter list that is that's
stuff between the rounded brackets you
would just put a comma after the first
parameter and then essentially repeat
the same thing for the second parameter
you'd have an argument label
followed by space followed by a
parameter name
colon and then the data type
now you want to use different argument
labels and different parameter names
obviously so that you'd be able to tell
it apart
now let's jump back to the playground
and add our second parameter so what i
would do in between these rounded
brackets in this parameter list is i
would just put comma and then i would
put my second argument label
my second parameter name followed by the
data type which is another int
now again xcode is going to throw this
error here
let's use autocomplete again add
two numbers you can see here it's been
updated to accept two arguments
so argument
just arg and arg2 so let's pass in two
and two
now we have to modify
our code a bit right now i'm still
getting three and that's because inside
this function code i'm not using
the parameter two yet we can change that
like that
so now a gets set to parameter
i mean para and b gets set to para 2
and then i'm returning a plus b
so now i actually get four in here
so one thing we can do with this
function is actually we don't need to
declare a equals para and b equals pair
two that doesn't really do anything
so we can get rid of these two constants
here and we can simply return
para plus para2 like that
straight off the bat now our function is
pretty simple
so at this point you might be wondering
why is it so confusing that i'm using
argument labels here in the function
call and then we're using parameter
names inside the function code
well
what you can do is you can actually
not specify argument labels
like that and just have the parameter
names and what it'll do is it's going to
use the parameter name both
as the argument label and the parameter
name so now
this is wrong you can see xcode here has
an error let's use autocomplete to see
what the new function looks like the new
function call and you can see here that
now the argument
labels are the parameter names
so we can also change our parameter
names at this point you probably don't
want to use para and para2 for your own
function so we can say
you know number one
number two if we have these as our
parameter names then you know this
changes as well
number one
number two
and then our function call would also
change
like that
okay
now you might be wondering why
why use argument labels at all like what
are they for
well using argument labels you can make
your function calls a little more like
natural english so let me show you an
example you can do something like this
add two numbers
so there's my first argument label
and
number two like that so let's take a
look at what
our new function call would look like
so when i'm calling a function
add two numbers using
two and two
right you can see how that reads more
like natural english and it makes
intuitive sense what the parameters are
going to be used for
meanwhile
inside
our
um
our function here if my parameter names
were using
right
or and it doesn't make much sense
right
um
you know if i didn't use
if i used these as the parameter names
like that
these would be terrible parameter names
because if my function is really long
this doesn't tell me anything this
doesn't tell me anything it doesn't mean
anything to me
while this function call still makes a
lot of sense when you call it
in terms of natural english but in in
the actual code in here and add two
numbers
you know adding using an n doesn't
really make sense so if you use the
combination of
argument labels and parameter names that
make sense
um you have this function call that is
like natural english that makes sense
and you also have meaningful parameter
names that you can use inside of your
function
okay so i want to show you
one more thing if you don't want to use
these argument labels at all
what you can do is replace your argument
labels
with an underscore like that
or you can replace one or you can
replace both so let me show you
what that
looks like
so i'm going to replace both the
argument labels with just underscore
let's take a look at
what that looks like now
so you can see now that
i just pass in 2
and 2 like that
no parameter names no labels no
arguments no nothing it's just you pass
in the input parameters like this
and
you these are your parameter names so
that's what you're going to be using
inside of your function
okay so just to recap
in this lesson you learned about return
values you learned about the return
keyword
and you learned about input parameters
and how to specify them what argument
labels are what parameter names are and
also how to omit argument labels
altogether
i hope you enjoyed this lesson if you
did please give the video a thumbs up
and please subscribe for more
hello welcome to learn swift for
beginners lesson nine in this video
you're going to be introduced to classes
which is an absolutely critical part of
the swift programming language if you're
going to be using it to build apps
i'll tell you all about it let's get
started
so i'm going to start off with a
hypothetical example so let's say you
have something like a blog post which
you would like to represent we might
have something like a variable here
for blog title right blog title can be
hello playground i don't know what kind
of article that would be
but we would have another variable for
the blog body and this is the you know
text of the article or the blog post
and then we might have something like
blog
author
which in this case let's just put my
name here
so you can see here
this is the data for
one blog post
now let's say i had two blog posts what
what would i do in this case
i might have another set of variables
down here and of course i can't have the
same variable names
so let's just append two to these
these variable names
and let's say this is
i don't know
this article is goodbye playground okay
now this is what i have for two blog
articles now what if i had 10 what if i
had a 100 how many variables would i
have then it it'd be a ton right it'd be
a mess
there needs to be a better way to
represent a blog post to kind of group
these variables together
and there is
in fact that's what a class is
you know how you learned about the
different data types back in lesson two
you learned about the string data type
you learned about the int data type
float double boolean
all of those are data types to represent
different types of data right
well with classes you can define your
own custom data type so what we're going
to do here is we're going to create our
custom data type
called blog post for example
you can do that with classes
let's take a look at the syntax for
declaring a new class
so first of all you have the class
keyword
next you have the name of the class and
this is going to be the name of your
data type then you follow by two curly
brackets
and inside those two curly brackets
is your class definition
let's take a look at this back in our
playground
so for example
up here let's create
and define our class so first i would
use the class keyword
and then i would create a
name of the data type or the name of the
class in this
case let's put blog post and notice that
this time i'm starting off with a
capital letter in fact all of the data
types in swift start off with the
capital letter so we should follow the
same convention always start off your
class names with a capital letter and
that's different from what we've been
doing with variables and constants and
functions
okay then i have these two curly
brackets like that
what do i put inside of my blog post
class
well
why don't we put
this stuff right here i'm just going to
cut it
and i'm going to paste it inside here
and then i'm going to delete this right
here
and i am going to
delete this text
inside these variables inside my class
and leave them empty and i'm going to
explain why in a second
okay so just like that we've defined a
class called blog post
and this class has three properties
now a property is just a variable
declaration like this but inside a class
it's called a property and you're going
to see why in a second why it makes more
sense
and because
um this blog title blog body blog author
is inside
of blog post it it's kind of redundant
to name them like this
so i'm just going to name them title
body and author like that
okay so this
this represents our blog post right here
now that you've defined what a blog post
is let's create an actual blog post
because remember this class definition
right here this is just
a definition of a data type you're
defining what a blog post data type is
right so that's not an actual
blog post just like how this is a string
that's not the definition of a string
that's an actual string so
in order to create an actual blog post
we're going to type in the class name
followed by two rounded brackets like
that and just like that this is a new
instance of the blog post type
and it's called an object or blog post
object
so when you define a new class using the
class keyword that's what's known as a
class definition or just class
but when you create actual
instances of that class
those are called objects
you can think of your class definition
as a template or a blueprint
and you use that template to create
actual tangible
blog post objects
so let's jump back to the playground
here this is a very important concept to
understand
we've defined a class called blog post
here it's got these three properties or
you can think of them as attributes of a
blog post and then down here like this
we've created a new blog post object now
this blog post object has
a title it has a body and has an author
but all of it all of them are empty
right now so what we're going to do is
we're going to assign this blog post
object into a constant let's call it my
post like that so what we've done here
is we've created new blog post objects
we've assigned it to my post
and now why don't we try setting the
title of this blog post and the body and
the author
what we would do is say my post
right that's referring to this new
object and then we press dot
and that lets us access those properties
which we've defined in the class
definition
set the title
to
i don't know hello playground i think
that's what we had before
let's set the author of this one
and let's set the
body to
hello
okay just hello
now if i print
my post dot
author
i would get my name
now let me show you something else we
can create a second
instance
of blog post or a second blog post
object and let's call this my
second post and we're going to set this
to a new blog post object like that
and we're going to say my second
post.title
equals
goodbye
playground and
we can set the author to
someone else let's say
um
john travolta i don't know why that
suddenly popped into my head
and
uh let's just do hello again
now
this is a second
my post object this is
different from my post these are
completely
two
different blog post objects
both of them contain these three
properties which we can set because
that's what we've defined here in this
class
now another very cool thing about
classes is that you can put functions in
them
right you can see how all of the lessons
so far are coming together
let's create a new property for this
first let's say
a number of comments equals zero this is
the number of comments in the blog post
and we're gonna define a new function in
this
blog post class we're gonna say
add comment okay
and we're not gonna worry about the
comment text just yet
let's just define this
so notice that in my function definition
i have these two curly brackets again
inside here this is going to be my
function code so inside this function i
am just going to increase the number of
comments by one this is all stuff that
you should have learned already in the
previous lessons
now okay so now every single blog post
object is going to have this function
now how do we access it
we simply go my
post
dot you can see now in the autocomplete
that there is this function called add
comment and it doesn't have any return
value it doesn't return anything so the
return type is void right there
let's call this function okay
see what happens so add comment
you can't visibly see what happens but
let's print
my post dot
number of comments
you can see that it's one
okay now let's print
my
second post
dot number of comments
what would you expect
this to print out
it prints out zero
why because we haven't called the add
comment function on my second post
we just did that with the first post
each of these blog post objects
maintains its own properties
changing the properties of one object
does not affect the other even though
they're cut from the same cloth right
they're both types of blog posts they're
two independent entities and they
maintain their properties separately
now there's a lot more to classes but
fundamentally i want you to understand
what they are
so i'm not going to make this video any
longer than it needs to be i just wanted
to introduce classes to you i hope you
can see why classes are a fundamental
building block to organize your
information so thanks for watching
please give this video a thumbs up if it
helped you and please subscribe for more
hello welcome to learn swift for
beginners lesson 10. in this video
you're going to learn about inheritance
otherwise known as subclassing which
allows us to build upon previous classes
which we've already defined and it saves
us a lot of time and effort and work so
that we don't have to keep defining
classes that do similar things okay so
let's get started and see how this works
let me start by doing a small recap of
what you've learned in this series so
far so you learn about variables and
constants to store and keep track of
data you also learned about some control
flow and conditional statements so that
you can express logic and make decisions
with your code and then you learn about
functions where you can define blocks of
code that perform specific tasks as a
way of organizing your code into more
manageable chunks and then you learn
about classes which is
further away where you can organize
related code and related functions
together as well as related variables
in the form of properties and then today
you're going to learn about inheritance
aka subclassing as a way to further
organize your code okay so let's take a
look at uh inheritance in a playground
so i'm going to launch xcode here i'm
going to get started with
a brand new playground and let's call
this
inheritance playground
okay let's just save it on my desktop
there and get rid of this line of code
so let's say that the app we're building
is kind of like a car simulator or
something like that and we need to
define a class that represents a car
so we're going to start by creating a
car class just like that
and some of the things that it may have
is for example it needs to keep track of
a top speed right because different cars
may have different
ranges for the top speed
i'm just going to initialize that to 200
so there may be a whole ton of other
attributes or properties to do with cars
but
for demo purposes i only need one so i'm
not going to go further than defining
top speed there and i want to define a
function so
a car
by definition is a vehicle that can be
driven right so i'm going to create a
function
called drive
just like that it doesn't accept any
parameters
and inside this function it's going to
perform all the code that
we need to drive a car
but you know for this demo i'm just
going to print
driving at
and then i'm going to put in top speed
like that so this
um this value in this top speed property
gets substituted in there and then it
prints out driving at whatever this
value is 200. so when i call the drive
function it's going to print this
statement out into the console
okay so we've defined our class here
that represents a car
and in the previous lessons you've
learned about how to create a new object
right from the car class
so
why don't we declare a constant
called my ride
and we're going to create a new car
object and assign it into the constant
myride
just like that we've created a new car
object now let me try
accessing
top speed right you press dot and then
you can access the
property there so you can see
it's running the playground okay you can
see 200 there and let's try calling the
function myride.drive
that
and you can see it says driving at 100.
okay so now let's say that in this
driving simulator app i also have
something called a super car or maybe a
future car so it's the car of the future
for example and it can fly so it's the
flying car that it will probably come in
the future so we can define another
class to represent that and we can call
it future car right
and again this future car because it is
a car still it's going to have a top
speed and let's say this top speed is
250 like that
and it's also got a function
called
drive and because you can still drive
this car
and again it's just going to print you
know driving at
top speed
and also this car can fly
so let me define another function that
represents
you know
uh flying the car so
flying i'm just gonna call it flying
like that
uh so here we've defined our car class
we've defined a future car right here
if i want to create another
um let's call it my new ride this is a
constant and this time i'm going to
create a new future car object like that
and then my new ride you can see
has fly now right it has drive and it
has top speed now let me ask you this
question see you can see the
similarities between car and future car
right they both have the properties of a
basic car like a top speed and they both
have this drive function which is very
very similar in fact it's actually
identical so this is pretty redundant
right there's a lot of redundancy
between these two class definitions so
this is where inheritance or subclassing
comes into play and is very helpful
so what inheritance allows us to do is
say that
one
class inherits from another class
and
essentially what that means is that
if future car inherits from car it's
going to inherit its properties and
functions so you don't need to redefine
them inside future car so let me show
you what i mean here
let's in future car let's delete this
top speed property and let's delete this
drive function
and what i'm going to do instead is i'm
going to make
future car inherit from car and the way
you do that is after the
class and then class name you put
colon like that and then you put uh the
the class that it inherits from so in
this case i would put car
so in this sort of relationship we have
car at the top
um and we have future car at the bottom
inheriting
all of the properties and the functions
from the car class in this case future
car would be called a subclass of car
and car would be called the superclass
of future car
and some people might call it the parent
class
so carr
is the super class or the parent class
or maybe simply the parent of future car
let's go back to our playground and take
a look at what this means
for our code here
so you can see that my ride is still a
car object and it still has top speed
and it still has drive
but take a look at
my new ride right it's a future car
object
and remember inside future car we've
just defined fly we haven't defined
anything else in here
but if i type in my new ride and i
press dot here and let autocomplete do
its thing you can see that future car
actually has a drive function and
actually has a top speed
so
you know if i do top speed
you can see it's 200 and if i do drive
you can see that now future car or my
new ride rather is also driving at 200
and furthermore
actually my new ride can also fly
okay so there's flying
now there's actually a problem here
because
right now my car and my future car
they're both driving at the same speed
but remember the future cars are faster
right initially i wrote the top speed
was 250.
so in this case what we can do is to do
something called overriding
and that allows you to take a function
or a property from the parent class or
the super class
and redefine it to
essentially that's where the word
override comes from so you're overriding
the parent's version of that function
and you're providing your own
implementation or your own version of it
now let me just do it here so you can
see what it means so
we use the override keyword like that
and then we have to declare drive
exactly as it is in the parent class so
uh
what we're doing is we're going to say
print driving at and we're going to
instead say top speed plus
50
because this guy goes faster so now you
can see that when i call
this guy when i call
futurecar.drop
it doesn't use
the parent class's drive function it
uses its own overridden definition of
what drive is
right so that this is the code that it's
running here
and you can see it's driving at 250.
okay so that's an example of overriding
to provide
your own custom functionality
now inside this overridden method there
is
a way that we can access still
the parent functionality and you can do
that by using the keyword super so let
me show you what i mean
inside this overwritten drive function i
can actually access the parent class
the definition
all the functions and properties in
there if i type in super dot
and then i can access drive so when i do
this super refers to the parent class or
the super class
and this drive function is actually
calling this guy up here
right so in this case it doesn't make
sense you can see in the console
when i type in futurecard.drive it
you know it calls the original
definition of drive and then it prints
this
you know its own definition of drive so
you know in this example it doesn't
really make sense but sometimes when
you're building your apps
what you want to do is add functionality
and not override the functionality if
that makes sense so you don't want to
replace
what's
in the parent class you just want to add
to it and so you can do that if you you
know you can call the original
definition and then you can add your own
code before or after that
to provide additional functionality so
in this case maybe i'll just change the
statement here
and
boosting at
you know 50 or something like that so
let's see
so now you can see that
this is my original car right when i
call drive it says driving at 200 and
then my future car is driving at 200
and it's doing something extra
and so that's that's how this overridden
function works
okay so this is a simplified example of
how subclassing works
but it's essentially how it works and
it's very predominant in the swift
programming language as i'm going to
show you in the next lesson
as you can see inheritance allows you to
save a lot of work by taking what's
already there
and then improving it or providing you
know alternate definitions so you don't
have to redefine everything all over
again but you can build upon the classes
that you already have okay thanks for
watching please help me continue to
create more videos for you by giving
this video a thumbs up and subscribing
to the channel
hello welcome to lesson 11 of the learn
swift for beginners series in this
lesson i want to introduce to you ui kit
it's an apple framework that contains
many of the classes we're going to need
in order to construct ios apps
alright so let's dive in and see what's
available in ui kit
so like i mentioned in the intro for
this video the ui kit framework is
essentially a library of classes that
apple gives us to build apps with when
you think about it there are a lot of
common elements to any sort of app for
example
apps may have views they may have
buttons you know all apps are going to
have
things that you need to present to the
user
apps are going to need to handle user
interaction from the person using the
app and so on and so forth so
to build that functionality out every
single time you're going to build an app
is extremely tedious and not to mention
complex and complicated so apple has
provided ui kit for us to use
and it contains a ton of pre-built
classes for us to handle all of these
common things
so here i'm looking at the ui kit
reference guide
which contains a list of all of the ui
kit classes that are available for us to
use i'll link to it in the description
below the video but if you want to look
for it yourself
just go into google and type in apple
space ui kit don't just type in ui kit
because
the first few results for that query
isn't the apple ui kit so just type in
apple space ui kit to find the
correct one in the first result
it was also essential to learn about
inheritance before i told you about ui
kit because many of these classes
inherit from each other they build off
of each other
so they don't redefine things and
this reference guide used to be kind of
organized in a hierarchy so you could
see which classes inherited from other
classes but since they've
changed it and they've made it kind of a
listing so you don't get that but i did
a google search and i found
an image that i'm sure this is not the
complete
ui kit because this image was from 2012
i think
yeah you can see here in the url it's
from 2012 but it does
give you an idea of how the classes are
organized so you can see at the very
top of this tree if you can imagine
this left side being kind of at the top
of the tree
and this right side being the bottom of
it if you take for instance this ui
button class which represents a button
that the user can tap on the screen ui
button inherits from ui control which
inherits from ui view
and if you just follow this line it
inherits from ui responder and finally
from ns object
so that ui button class is a culmination
of all of that functionality you know
from that chain and
let me just take a little moment to
explain
it to you so you can see how that ui
button class is finally constructed so
this ns object class is the root class
of everything you can think of it as the
big grandfather or granddaddy and what
this ns object class does is it provides
that basic functionality that allows you
to create an object from a class
definition so that's something we went
through
in part one of the classes lesson so
this ns object class kind of gives you
that functionality and if we take a look
at what was the next one down the chain
so the ui responder class so this ui
responder class inherits from ns object
means that it contains that foundation
that's going to be needed by you know
all of these ui elements or user
interface elements
okay so the next one down is a ui view
so ui view inherits from ui responder
which inherits from ns object so ui
uiview gets all of that functionality
and on top of that
the ui view class provides functionality
for displaying something onto a view so
a ui view is
something that you can show to the user
so it contains all of that functionality
and code and then next in that hierarchy
down to the ui button we have ui control
now ui control contains all of that
functionality before it following this
line here
and on top of that contains
basic code and functionality for a user
element control
so stuff that is specific for
displaying onto a view
handling user interaction and events
and responding
so then we have a specific type of ui
control and that is the ui button which
is pretty self-explanatory looks and
behaves like a button with certain
button events
so that's just one example of you know
the path you can see that there's a
whole ton of classes and there's even
more now so whenever you go and you know
before you go and do something with your
app
chances are
you can probably leverage something from
ui kit to build off of rather than
building something from scratch
so in this video i just wanted to give
you guys an introduction to ui kit
because we're going to be using a lot of
classes from here and every time i do i
will try and remember to reference this
guide or at least link to it so you can
take a look at these classes
it's very useful and handy to have at
your fingertips
because you can click into these classes
and then you can find out for this ui
button class what sorts of functions it
has and properties it has that you can
use and leverage and how you can perform
specific things with the button or with
that class
and furthermore i might do another video
series where we go over specifically
different ui elements
because i think that would be useful for
beginners to understand how to use for
example like a date picker or text field
or slider or switch or something like
that
so that might be a separate series on
just ui elements
please give this video a thumbs up and
subscribe to my channel to help channel
grow
hello welcome to learn swift for
beginners lesson 12. in this video we're
going to talk about initializer
functions for classes
these guys exist to make sure that when
you create a new object from your class
that that object is ready to be used
plus you can customize these initializer
functions to set up the object any way
you want when you create a new instance
of the class
let's get started and see what that
means
[Music]
so what i've got here is a playground
and i wrote down a basic class here
called person
and this person class has got two
properties right now it's got a name
property which i've initialized to an
empty string
and also it's got an age property which
i've set to zero and that is an integer
now you learned about classes in a
couple of lessons back and you learned
about how we create objects from classes
right
and in order to create a new person
object i would say something like
var
let's just use the variable
a
equals person
like that and we open up and close
brackets um beside the class name like
that and here i've got a brand new
person object
and if i go a dot name
you can see that it's an empty string
and if i go a dot age you can see that
it's zero
so what's actually happening when you
create a new person object here and you
write these brackets don't these two
brackets look like you're calling a
function but actually what's happening
is you're calling the initializer
function of the person class but you
might ask we don't have one defined in
here what initializer function are you
talking about let me write it out by
default it exists
and if you don't customize it you don't
really have to touch it but that
initialization function looks like this
it just uses the keyword in it and it
has these two brackets and then
in here in between this just like a
function you can define code
in here
to set up your object
so what's happening
when you
create a new person object with this
line of code here is you're actually
calling this init function of the person
class and inside here you can actually
write code to customize things so for
example i can say name equals chris
and age equals
i
believe i'm 33 i think i've lost track
but
so what's going to happen here when i
create a brand new person object is it's
going to call this init function and
it's going to set these two properties
to these two values here so as you can
see now
name is chris and age is 33 when i
create a brand new person object
now remember how i said that you can
actually customize the init function to
set up the object the way you want it to
be set up
and we can do that simply by adding some
parameters into this init function just
like we would
for any function that we set up so for
example i can say
i can say n
is a string
and a is an in
so now i have to pass in these two
values so let me just erase this part
here
and i'm going to create a new person
object and now you can see that the
autocomplete shows me this
so for name i pass in chris
and for the int i'll pass in 33 but
instead of setting this stuff to the
hard-coded values now i can set up to
what is being passed in here
so that's n
and that's a
right when i'm creating a new person
object here i'm passing in these values
that go in through this init function
and then it sets the properties to those
values which i pass in
now remember if i don't want these
parameter labels all i need to do
is go like that and you we learned this
through the functions lesson so you can
review that
if you forget
why this is these are the argument
labels by putting underscore there we're
basically saying we don't need the
argument labels
now while we're on this topic of
specifying these parameters here
oftentimes and sometimes i catch myself
doing this too is that when we're
passing in these parameters the name and
age and you're intending to set it to
these properties here
there's a tendency to name these
parameters exactly like
the property names because after all you
name these property names to be
descriptive right of what they represent
so in the parameters you might be
tempted also to name them the same thing
well what happens is you get into this
situation where you're trying to set
this parameter
into this property name but they're both
named the same thing so it's a little
bit ambiguous so that's where you can
use this keyword called self
and
what how you would use it is you would
say self.name
equals name so self refers to the object
that is being created so you're saying
to set the name property
of the object to
this name parameter so that's how you
distinguish between
uh if the property name and the
parameter name is the same
so i would do the same thing here like
that
so then this age refers to that guy and
self.age refers to the actual property
there
now another thing i want to point out is
that
i can no longer
call
person like that
because there's no init method like that
what i can do is i can actually
have multiple
initializer methods so if i do this
let's let's say this is var b
equals this person object well
this b
dot name
is empty and b dot h is zero right
because these guys haven't been set
after all i'm calling this
initializer function here that doesn't
set anything
whereas this guy this initializer
function actually sets the name and age
to whatever we pass in
now there's one very important thing we
haven't talked about yet regarding init
functions
i mentioned in the intro to this video
that the init functions are there to
make sure that the object is properly
initialized and all of its values are
set
making the object ready to be used so in
this case right here for the person
class i've declared two properties and
i've already preset them
or
initialized them to these values here so
really the init function has nothing to
do even if i did nothing as is
in this case right here
the object would be ready to use because
these properties have values
in the next lesson i'll show you how you
can sometimes if you need to declare
these properties
without setting or initializing them to
values so it would be something like
this
you wouldn't write it out like this but
just as an example you wouldn't set it
to anything so there would be no values
in here
in that case when you create a new
person object
the init function would be responsible
for making sure that these guys do have
a value because if not all of these
properties are initialized to values
then the object is not considered to be
ready to be used so the init function is
there to make sure
that
the values are set
and like i said
so far you haven't learned about how to
declare these
properties right here without sending
them to values i've always have set them
to something but in the next lesson
you'll learn how to do that
and then we'll dive a little deeper into
initializer functions and talk about how
there are two types called designated
and convenience initializers and so on
and so forth okay so thanks for watching
remember to give the video a thumbs up
and uh subscribe to the channel if you
haven't already
hello welcome to lesson 13 of the learn
swift for beginners series
in this video you're going to learn
about optionals and it's probably one of
the most confusing things for beginners
if you've ever looked at swift code and
you've noticed exclamation marks or
question marks in the code then you've
come across optionals so let's get
started and find out what it's all about
[Music]
so right here i have a playground and i
have declared a class blog post in fact
if you've seen
episode nine
the first lesson on classes then this is
going to look familiar because this is
the example that we used for lesson nine
when i first talked to you about classes
now we declared a couple of properties
up here
for our blog post class
and these properties they represent
certain things about what a blog post
might have so for example the title the
body the author number of comments and
you can actually safely ignore this
function so i'm just going to remove it
because we're going to focus on this
stuff up here you'll notice that each
time i declare a property right here i
immediately initialize it to a value so
title body author are all initialized
to an empty string right when they're
declared and comments is set to zero
right
right when it's declared
now this is all fine and dandy but what
if you actually want
some of these properties to be empty
for example what if i want to tell if
the blog post has an author or it
doesn't have any author
you might argue that well i can just
check if author is equal to an empty
string and if it's equal to an empty
string then maybe there's no author
well what if the author isn't actually a
string what if it's actually
you know we have another class here and
we call it
person and let's say that
there's a name and we'll initialize the
empty string but you know okay so in
this case
person
is assigned to author so
you know blog post has an as an author
because it has this person object so how
do we distinguish
um there being no author for a blog post
well
you have to be able to declare an author
property and leave it empty because some
blog posts may not have an author so the
way to do this is if you remember from
way back then maybe
lesson
lesson 2 on data types i think
you can actually specify for your
variables the specific data type that it
can store if you don't specify it
basically the data type is inferred from
what you assign into it okay so for
example if i wanted the title
to be able to be empty
i would have to declare the type
i'd get rid of this equals empty string
because we don't want to sign in
anything to it right we want to declare
this property but leave it empty
i would do it like that i would you know
do the colon specify the specific type
and then i would put question mark and
that is an optional right there
so
when i declare this title is empty
and this part basically tells us that
the data type of title is string
and this question mark
attached to the string data type tells
us that it could be
nil which means nothing or empty it
could be nil
or it could actually contain a string
so contrast this with the body property
here this when it is declared is
assigned this empty string so it's
always going to have a value right
whether it's empty string or maybe in
the future we assign some text into it
it's going to have some text
but
you know this title
property could be empty in fact it is
empty right now as we declare it
so going back to this example with the
author
potentially some blog posts may not have
an author so we can't just you know
initialize the author property to a
person object because that would mean
all blog posts at least have a person
attached to the author right we want to
make this property able to be empty
right so the way we do that
again is we specify the specific data
type
put the question mark there next to the
data type and we get rid of that part
because we don't actually want to assign
anything to it okay so in this way
we have a blog post class
which has
an optional title property has body
which is initialized to
an empty string so it at least always
has a value
uh and it may or may not have a person
you know could have nobody assigned as
the author or it could actually have a
person object assigned as the author and
number of comments will always have a
value and starting at zero
so you're going to want to pay attention
now because i'm going to tell you how
you should think of these optional
properties that we have here and this is
sort of metaphor or visual that you can
think of
that i was taught when i was learning
this stuff
and that is to think of the title
property
this optional
string it could optionally contain a
value or not think of it like a box
it's labeled string but you can't see
what's inside the box you don't know if
there's actually a string object inside
or it could just be an empty box
it could be an empty gift box if someone
if you've been really bad and someone
gives you an empty gift for christmas
that's never happened to me but if it
has to you let me know in the comment
section below but anyways you can think
of
an optional property
like a box
that may contain the actual object or it
may not
so how can you find out if there's
actually
uh the string object inside or not well
you have to unwrap that box right you
have to unwrap that gift
in order to look inside and see and get
at the
actual object
and that's exactly what we have to do in
code now with our optional properties so
let me let me create a new blog post
object here let me say
post equals
blog post like
that and what we're going to do here is
we're going to say hey print out
post dot body
plus
i don't know plus hello something like
that okay so it basically just prints
out hello because body is empty but
let's just assign it to something
like that
so then we have something like hey hello
right that totally makes sense because
body we've initialized it to hey
right
when we create
uh the blog post object it's already set
to hey and then we concatenate hello to
it so when we print post dot body plus
hello you know you're accessing that
property and then you're pending hello
anyways that makes sense so
we can no longer do that with something
like the title
right because that's an optional it's
it's wrapped up in a gift box and you
don't know if it's empty inside or if
there's actually a string object inside
so you can't blindly use it you have to
unwrap that gift box and and check if
there's a value or not and then use it
so now before we use title we have to
check if there's actually a string
object or if there's actually a value
inside that optional and the way we do
that is we do something called optional
binding
okay so
it's kind of like an if statement so you
say if
but then you use the word let and if you
remember
using the keyword let is declaring a
constant right
in fact that's exactly what this is
you're declaring a constant here
if let
actual title
equals title
and then you open up these curly
brackets so
what you're doing here is you're testing
sorry not title i meant post dot title
because this is the
optional property here
what you're doing here is you're saying
that you're testing you're unwrapping
this
this title property this optional and
you're saying if there is
a value in there then assign it to this
constant called actual title and then
inside here um you can use actual title
as the value but if there is
nothing inside this optional and if you
unwrap it and it's empty it's nil
then don't execute this code inside so
that's why it has an if statement
here
you're basically testing to see if
there's a value inside this optional if
there is you assign it to this constant
and then you use this constant inside
here
uh if there isn't then it's just going
to skip over this whole if statement so
in here we can safely now we can say you
know print actual title
uh plus
um
i don't know salute
so
there is no value
in title so it actually skips all this
but let let's say for instance we say
here post.title equals
um yo
like that
so now you can see when it does this
optional binding and it
unwraps this title because we have
assigned something into it here it finds
that hey i unwrapped the optional there
is a value i'm going to assign it to
actual title so inside this if statement
we can use
actual title
and do this
but if i didn't have this line here
let's comment this out you can see that
it it completely skips this and it
doesn't crash
or do anything like that because we're
safely you know checking if there's a
value inside that optional first and
then we're using it
now there's always
different ways of doing things so
in the swift programming language
there's actually a way to be a cowboy
and skip all this if you don't want to
check it
and you just want to use the value you
know you know there's something inside
what you can do
is you can use
you know you're going to not check it
you're just going to use it
you can
be that it would be post dot title
and you put this exclamation mark and
this is called force unwrapping so what
you're telling xcode is you're saying
that hey you know i know there's a value
in here i don't need to check it i just
want to unwrap it
right away using this exclamation mark
and i want to use whatever is inside of
there
right in this case it's yo
so here we're you know we're accessing
post dot title it's an optional property
we don't care we're gonna force unwrap
that
and we're gonna take out that value and
use it you know
and so if you know there is a value
inside you can do that but it gets a
little dangerous because for example if
there happens to not be a value in there
and you're force unwrapping it and
you're trying to you know use the value
well there's an error because
and this is the error you get fatal
error unexpectedly
right because when you use this
exclamation mark you're expecting that
there is a value
unexpectedly found nil when
unwrapping an optional value
right that is exactly what i was telling
you you're forced unwrapping the title
and you're trying to use it but it was
actually nil so you actually get a crash
and in your career of building apps you
probably will see this error
unexpectedly found nil so now you know
why
so the safer way to go would be actually
to use optional binding so i'm going to
press command z now
command z for the americans
i'm going to undo
undo all right
do something like that and this is
optional binding so
another way
where you can test before using is just
oops
it's just with good old-fashioned if
statement and testing if it's nil so you
can say something like
testing for nil you can say if
post dot title
is not equal nil
then print
post dot title and because you have
tested it that it's not nil in this if
statement you can go ahead and force
unwrap that
and use it
right so that works you can safely
use force unwrapping because in this if
statement you've just tested that it's
not nil
okay
now the reverse if you want to check
that it is nil
is post dot title equals equals nil okay
it's not equals nil
a lot of beginners make this mistake and
they use one equal sign but one equal
sign is for assignment remember that so
if we're going to test for nil you're
going to use two equal signs like that
and this is like
optional
contains no value
okay
optional contains value and in here
for optional binding
optional
contains a value
so as with all of the other things we're
learning with swift
we can go deeper there's additional
things to learn about optionals like
optional chaining and other ways of
using optionals but this is your
introduction i wanted
to tell you about what the question mark
means and what the exclamation mark
force unwrapping and how to check an
optional before using it
i wanted to introduce you to these kind
of high level concepts and practically
speaking you'll be using them most of
the time like this
and then in the future we'll touch upon
the more complex things about optionals
also you might be wondering
why why and when you would ever use
optionals but let me tell you you
definitely will use it when you're
building apps and when we do build our
apps together you'll know what they are
and you'll know
how to declare optionals and how to
unwrap them and how to check if they're
no because you've watched this lesson
okay so thanks for watching
and please subscribe and thumbs up and
share the video with other people you
know who want to learn swift as well
hello welcome to lesson 14 of the learn
swift for beginners series in this video
you're going to learn about properties
which is something that we have been
using already together
since the classes lesson but we haven't
formally introduced them yet so this
video is for that
in addition to that i'm going to show
you some other cool things you can do
with properties that you can't do with
variables
okay so let's get started
[Music]
so here i have a playground which
defines two classes blog post and person
you might recognize this from previous
lessons
and in both of these classes we've
defined some variables here well
properties are nothing more than
variables that are associated with a
class like this
so for example in this blog post class i
have a title property body author and
number of comments and if i create a
brand new blog post object from this
class let's say
let
my post equals new blog post like that
and then in order to access this title
property
i would use the dot notation
i would say my post dot title and i'm
going to assign something to this
property and let's just call it title of
post like that
and in order to retrieve that value from
that property i would just
use dot notation again
and this would return
the value inside that property
so you can see that property is just
like a variable where it stores a value
and you can retrieve it but i don't know
if i mentioned this before and that is
that
properties are independent
between objects so remember
we have defined this blog post class
right here and from this class
we can create many blog post objects
for instance here i've created a blog
post object and i've assigned it to my
post now let me create a second blog
post object
i'm going to call this my post
2. and i'm going to create a brand new
blog post object from there
so i have assigned title of post to the
title property of this guy right here
right
that
doesn't affect my new blog post object
so
i can assign my post to dot title equals
another
title
like that
and if i display this title
you can see that it shows another title
so
the
properties are really variables that are
attached to
the blog post objects that i create and
although each blog post object has a
title property
the values that they store are
independent of one another
okay so the second thing i wanted to
point out with properties is that when
you're working inside your class so
let's say we're working on this blog
post class and we create some
functions here
let's say add comment
you know we're going to create a
function
like that
and we're going to create another
function maybe called
share
share article okay these don't really
have to do anything i'm just i just need
to create two functions for the sake of
creating two functions to demonstrate
this purpose okay so
just disregard what what i'm calling
them because they're not really going to
do that function
okay so what i wanted to point out is
that
these properties that you define inside
the class
they can be accessed
inside any of the functions inside that
class so inside add comment
you know i might be performing some code
to add a comment
and i would be able to access let's say
um
you know i can print
title or something like that right that
would access this guy well actually
that's an optional so
using what we learned let me just force
unwrap it
but my point is is that i can access
these properties here you know or i can
print
let's say body for example
you know and here likewise i can also
print body
within all of the functions inside this
class i can access
any of these properties up here and i
can set them to from within any of these
functions however
if you declare a variable inside of a
function that is what's called a local
variable and the existence of that
variable is limited to the scope of that
function so what that means in plain
english is if i declare a variable here
let's say var
my comment
equals
you know some comment like that
i would not be able to access this
variable
inside this function here so if i try to
you know print
my comment
you're going to see it
throw an error here
saying that
my comment was never used oh wait that's
regarding this guy right here so this is
just an optimization xcode this yellow
little triangle means
that
it's a warning it's not really an error
so it's fine xcode is just
warning you that you declared this my
comment variable and you assigned it
something but you never used it so
consider
consider changing its name to
an underscore
which
which is an optimization but we are
going to use it the xcode is just
proactive because every time you're
typing code it just scans your code and
it tries to tell you about these
optimizations that you can do okay so
that's kind of a side note
back to the main point i was trying to
make and that is if you look at this
error here
on use of unresolved identifier my
comment that means that xcode doesn't
know what you're referring to when you
try to print my comment here so even
though we declared it here and we
assigned it inside this function
this variable because you declared it
inside here
is the scope of this variable
or its existence is limited to whatever
is
inside
these two curly brackets you know it's
limited to the code inside this function
now if i wanted it to be accessible
everywhere you know i would
create a property
and i would use that instead so that's
probably something you're going to get
used to as you're
doing more coding is the scope of where
you declare things so this is called the
local variable because we're declaring
it inside a function and these
properties that we declare up here to
hold values are accessible
inside the whole class
so what that means is that let me just
delete these two functions for now so
what that means is that if you have a
function that
let's say calculates a result or
performs some sort of calculation like
for example
um
add
up comment
total or comment counts or something
like that and the point of this function
is to maybe sum up the number of
comments that this blog post has
and then at the end of the
whatever you know you're performing
calculations here
um do
some calculations
and come up with as a result
arrive at a result
now what do you do with that result
right
um you can either
and you learn this in the functions
lesson is that you can specify a return
value so
this um this specifies that when you
call add up common counts
it's going to return a number for you
so now you can say you know return
whatever the result is whatever variable
it's stored in right you can return it
to the caller another thing that you can
do to make it
accessible later on because remember
any variables that you declare inside
here are local variables and they live
and die
inside this function here
so if i didn't do the return value route
and i arrived at some sort of calculated
result and i wanted to save it for use
for later on i would probably
assign it to a property so i can say
number of comments equals
whatever result that i arrived at and by
doing this when i call this function
it's going to do some calculations
calculate the result
the total number of comments right and
it's going to assign it into this
property
and now
i can use the number of comments in
other functions or later on
if i left it as a local variable
it would again when this function
finishes that would be lost
okay so that's the difference between
the lifetime or the scope of property
versus local variables
and now for the third thing that i want
to show you in this lesson is something
called computed properties and it's one
of those things that makes properties a
little more special than just plain old
variables here
so let me
let me get rid of these two here so that
we kind of start fresh and we're back to
where we started in this lesson
you can do what's called a computed
property and what that is is it just
returns
and what that is is it lets you do some
calculation and return a result when you
call a property so let me demonstrate
here so let's say that we have
let author equals
person
right so there is our author and let's
set
the author's name
to
chris ching which is my name
and now let's create a blog post my post
equals blog post
okay and
now let's assign the author
property of the post right let's assign
author into it
now author right here is
this person
right this person object that i created
and
finally let's set the title
to let's say
learn
swift for
beginners
okay so what do we have here we have an
author object which has the name set to
chris ching we have a blog post object
uh
with the author set to this person
object that i created and i also set the
title to learn swift for beginners
now
what i wanted to show you is
i'm going to create a computed property
up here
i'm just going to add a comment so that
just to make it stand out a little bit
so i can say var
full title
is a string and i'm going to open up a
set of curly brackets right
uh right after it
and what i'm going to say
is
check if title and author
aren't not nil
check
that title and author are not nil
because
title is an optional right an author is
also an optional and you learned about
these in the previous lesson
so you know what they mean they could
return nil which is nothing right when
you unwrap it
so i'm going to use an if statement just
to check
so if
title
is not equal to nil
and
and that's the double ampersand which
represents an end condition
so if title is not nil
and author is also not nil both of these
conditions have to be true
then i'm going to run this code inside
then
return
title and remember because title is
an optional
string right that means i have to unwrap
it to get the value inside and i'm going
to use the exclamation mark to force
unwrap it that means i'm going to tell
xcode i'm just going to unwrap that
optional and use whatever is inside
whether it's a value or it's or whether
it's nil
and i know for a fact that it's not nil
because i just checked it up here right
so i can safely and confidently do this
so i'm going to say
bye
and then plus
and i'm going to do the same thing with
author i'm just going to force unwrap it
and use it
okay so let's see what it's saying here
cannot be applied to string
and person that's right okay so author
is a person right so i can't
i can't append a person object
to the string what i'm meant to do
actually
is
i meant to unwrap the author right to
get the person object and then call its
name property so that's what i actually
wanted to do
okay so
right here xcode is complaining that
missing return in a function expected to
return a string
so this computed property here when it
gets called full title
it's supposed to return a string
and if title is not nil an author is not
nil it is going to return a string
but what if one of these things
are nil
either or
um in that case i'm just going to use
the else branch here
i'm just going to return
let's say
let's do another check else if title is
not nil
oops not equals nil
then return just the title
oops force and wrap that
finally if the title is nil then i don't
know what we can do other than
return an empty string
or let's say no title
let's do that okay
so this is awesome now this is a
computer property and
i hope you can see that from this
demonstration what that means
it's a property where basically you can
perform some code you can do some
calculation you can combine a bunch of
things
and return
a result return something so
if i say
down here
if i say my post
dot
full title what do you think it's going
to display
let me print it out because it's kind of
truncated over here
let me use the print so it prints down
in the console
it's learn swift for beginners by chris
ching
and i didn't have to set that right
because this is a computed property this
full title property is calculated by
grabbing the title
and appending by and then appending the
author name
and if we didn't have an author so let
me just
let me just get rid of this line here
for setting the author if we didn't have
an author it would just print out the
title
and if i get rid of the title and it
doesn't have a title then it's going to
print no title and that's all of this
logic here in my computed property
okay so that's computer properties
there's also
additional things which we won't cover
in this lesson we'll probably do another
video on properties and that is getters
and setters and property observers but
this is a really great start to taking a
look at properties so thanks for
watching please like the video and
please subscribe
hello welcome to lesson 15 of the learn
swift for beginners series in this video
we're going to revisit initializers and
i'm going to tell you about designated
initializers and convenience
initializers okay well let's get started
[Music]
so right here i'm starting off again
with the blog post class and the person
class
and of these properties here in the blog
post class
i'm actually going to uninitialize some
of these properties so i can demonstrate
for you
what we need to do in the initializer
because i mentioned before that one of
the jobs of the initializer is to make
sure that all these properties are
initialized and ready to go so even if
it is an optional that is considered
okay
when you're declaring your properties
inside your class there are basically
three different ways of doing it so
number one is this one where you
declare the property and you initialize
it to some sort of value right away so
that's this body property right here and
this number of comments property is
equal to zero
the next thing you can do is you can
declare a property and set it to
optional so you're specifying that it
could be nil or it could contain a value
but either way
you have to unwrap the value and you
have to check if it's nil before using
it
now the third way is probably the most
dangerous way and that is using the
force unwrap operator
so let me show you what that means
if i
get rid of that question mark and i put
an exclamation mark there and let's also
do it beside author so what you're
saying here is you're saying that title
basically is an optional it could be nil
or it could contain a value but you're
going to leave it unwrapped
so when i access the title property down
here and i say post.title
xcode is not going to
have that sort of safe
checking or warning us
that it could be nil it's not going to
provide any of those safety mechanisms
and it's just going to let us use it as
is
so we can assign nil into title as you
can see here it's nil
and we can use it like a normal property
right we don't have to
check if it's nil or not or rather it is
up to us whether we want to do it or not
but however if
you know the difference
the flip side
being that we make this an optional
now there are some safety mechanisms in
place if i just try to use this as is
xcode is going to warn us that hey you
know this is an optional you have to
check that it's not nil or you have to
unwrap it
first before you can use it so i might
have to say if let
you know actual title equals and this is
using optional binding so basically
we're checking
if there's a value inside the optional
first
you know if something could potentially
be nil it's probably safer to use an
optional value so that it forces the
programmer to actually check things
before using it now if you set your
properties like
that
then it could still be nil or could
contain a value but you can sort of
remove that safety checking that
optionals provide
so those are three different ways that
you can
set up your properties
what you cannot do however
is you can't
do something like that where you declare
a property
you don't set it to anything
you don't specify that it's an optional
or you don't specify that it's unwrapped
and you just leave it like that in that
case xcode is going to assume
that the initializer is going to set
those to some values
so let's declare our initializer here
like you've learned in the past
and inside here you can see that xcode
is still showing errors but if i
actually initialize these things
inside the initializer
let's say author is equal to person like
that
then xcode is going to stop complaining
because
remember when we create a new blog post
like this it's actually calling the
initializer so even though these
properties right here title and author
they're not set to anything they're not
optional they're not
unwrapped this initializer is going to
be called for sure when we create a new
blog post object and inside here
those properties get
set to some value they get initialized
and so at the end of the day this blog
post object is going to be ready to be
used
now this initializer right here this is
what is called the designated
initializer and what that means is that
this initializer function is guaranteed
to
fulfill those obligations of
making sure that all of the properties
are initialized before use
in contrast we can have something that's
called a convenience initializer and
what that is is you use the convenience
keyword followed by your initializer
method signature so i might have
something like this where inside this
initializer i only want to
provide a custom title
well you might ask if i call this
convenience initializer
how is
author going to get initialized
right so what happens is inside the
convenience initializer i call the
designated
initializer using the self keyword like
this
so now
and inside here let's set title equals
custom title
so now when i declare a new
blog post object and let's say i use my
convenience initializer like this
and i pass in a custom title like this
it's calling this
convenience initializer
but this convenience initializer is also
calling the designated one which makes
sure that at the end of the day you know
the uninitialized properties will be
initialized
and then after calling
that designated initializer then we set
title to custom title so whether i call
this designated initializer or the
convenience initializer
the title and the author properties will
be guaranteed to be initialized
and so the role of the convenience
initializer is simply for convenience
so that's the difference between a
designated initializer versus a
convenience initializer
hello welcome to learn swift for
beginners lesson 16. today you're going
to learn about how to manage a
collection of data in what's called an
array
if you're working with many pieces of
data it would be hard to manage them
with simply constants and variables so
let's take a look at how arrays can make
our life easier alright let's get
started
[Music]
now arrays are one of three collection
types that are available in the swift
programming language for us to use and
manage our data in this language guide
you can see a diagram of this
array on the far left side we're going
to come back to this diagram in a second
but first a definition
so you can think of an array as a
collection of data that is ordered by
indexes
now if that doesn't tell you too much
let's jump right into a swift playground
and i'll show you exactly how beneficial
they are and also how to declare them
and how to use them
so first i'm going to delete this
default variable here and we're going to
create a couple of
variables ourselves so let's say var a
equals dog
var b equals cat
var c
equals
bird
and now let's say i wanted to
concatenate or add the word my in front
of each of those values there so that i
would have my dog my cat and my bird
so i would have to do something like
this i would have to go a equals
my space
plus a
and this would result in a being my dog
because
we're adding the word my with space to
a and a is dog and then we're
reassigning that result into a again
thereby overwriting what was there
before so now a is actually my dog
i would have to repeat this for cat and
i'd have to repeat this with bird i
can't even use what we learned in the
previous lessons in regards to loops to
make my life easier i'd have to write
this out three times for each of the
variables
so here's the perfect chance to use an
array to organize this collection of
data
so in order to create an array with the
data already in it we're going to open
up two angle brackets or square brackets
if you'd prefer
and inside these two square brackets we
put each piece of data separated by a
comma
so we have dog
we have cats
and we have bird
so just like that we have an array with
three pieces of data
and if you remember what i said in the
definition
that arrays are a collection of data
organized by indexes what do i mean by
that well you can see that there are
three pieces of data here so there's
three distinct spots you can think of it
the left most spot here the beginning
is index zero or spot 0 if you'd prefer
to think of it like that the next one is
index 1 and the last one is index 2. so
arrays start at 0
and because there are 3 items here the
indexes go from 0 1 to 2.
and now if i quickly bring up that
language guide again you can see in this
diagram that in this array there are
five items and so the indexes for six
eggs is zero index for milk is one and
so on until it reaches four even though
there are five items because it's zero
based okay
so let's go back down here
so this is great that we have an array
here but we need some way to reference
that array so actually what we do
is we can create a variable let's call
it d
and we assign this array or this
collection of data into the variable d
so now if i wanted to access dog for
example i would write d
and then i would write square brackets
like that and in between the square
brackets i would put an integer
representing the index of the item that
i want so let's say i want dog i would
put 0.
so you can see here i would get dog all
right and so we can
print that out
and that would print
dog down here now if i change the index
to 1
then i would get cat instead
now let's do an example where we have
something like this
just to duplicate that i would say
let's say a equals
my
plus
d
zero
like that i can do b equals
my
that's my cat
and finally
i would get my bird but then i mentioned
that there was a better way to do it if
we leverage what we learned in the
previous lesson on loops well we can
let's take a look at using for loops and
simplifying our work here so remember
for loops will loop a piece of code for
a specified number of times and you can
see here that i'm working with index 0
and x1 index 2 so this becomes really
easy i can say four remember the next um
the next piece of the for loop is a
counter
so
you know it's my variable to hold the
current index
and then you write in and then you write
your range so i can write 0 0
sorry i mean 0.2
and this is going to loop from 0 to 2.
so you i think you can kind of see where
i'm getting at what i'm going to do is
print
my
plus d
and inside
here where i put the index usually i'm
going to put counter
and you can see here it took the
playground a little second but
that's exactly what i expected to do
here
so in the first iteration of this for
loop counter is zero right that's the
starting range so zero gets passed into
here and i would get this printed out
this is dog d at index zero right is dog
in the next iteration of the loop
counter is one and so i'm actually
accessing index 1 of my array d
so that's why i get cat
and then finally it loops again and
counters 2 and i would access this bird
index here
i want to show you another way
to use your for loop with an array and
that's simply to say
for
item
in d
so what this is going to do
is it's going to loop through all of the
items in the array d
and in each iteration of the loop it's
going to take that
item
or that piece of data
and it's going to assign it to item so
i can simply go like
this
so you can see that it gets printed out
again
right in the first iteration item is dog
in the second iteration it's cat and the
third it's bird so this is a pretty
simple way to write it and you can see
that it saves a lot of work from doing
it kind of one by one like this and one
by one like this
arrays in conjunction with loops really
powerful stuff
now with arrays there's other cool
things you can do let me just
make some space here maybe i should
delete this stuff
you can actually declare an empty array
so it's an array that would contain no
data at first and the way you do that is
just like storing things into a variable
or a constant arrays can only store data
of a certain data type that you specify
so since it's an empty array how you
would do it is you open up two square
brackets you put the data type inside
the two square brackets and that data
type represents the type of the data
that the array is going to store so i'm
just going to put string here
and then you end off with two round
brackets like that and just like that
now e refers to an array that is empty
right now doesn't contain any data with
the intention of storing string type
data in this array
now if you're going to create an empty
array like this you better be able to
add data to that array right so what
makes arrays really useful is that you
can add and remove data from that
collection so i can add or remove from
this collection right here i can add or
remove from this collection here let me
just show you how to do that there are a
couple of different ways
i can do something like this d plus
equals
two angle brackets like that again and
let's say i wanted to add
mouse
and now my d array would contain four
items as you can see here dog cat bird
and mouse in fact i can even add two
pieces of data at once comma
and then here
i could put owl for example so it would
add mouse and owl to that array so now
my array has
five items from zero to four
right starts at zero one two three four
make sure that you don't forget that
plus sign right here because
if you do that
then essentially you're creating a brand
new array with these two items and
you're assigning it to d and you've just
lost this data here
so plus equal
is for adding items
now seeing this plus equals you might be
tempted
to use minus equals
to remove items
like this
but that actually doesn't work
unfortunately you can't remove items
from the array like that what you have
to do is the array actually has
functions that you can call on it to
remove items so you would say d and then
you would press dot on your keyboard or
the period key
and out pops a list of functions that
you can call on this array
and using the append function is going
to do exactly like this plus equal is
it's going to add items into that array
but
let's look at the remove functions so
you have remove all
which is going to remove all the items
in an array
but you can
use this one here remove at and you can
specify the index of the item you want
to remove so if i put 0 like that that's
going to remove dog from my array so now
it's only going to contain cat bird
mouse and owl
now what if i don't want to completely
remove dog but i just wanted to change
that element right there at index 0. so
let me get rid of this remove line
you saw that you can access items in the
array by doing that right putting in the
index there well you can actually change
the item you can change what is assigned
at that index
by typing d
square brackets put in the index you
want to change
and using the equal sign to assign
something new into that spot
so here let's say turtle
and that is going to now change your
array
if i
print d
oops zero
i'm going to get turtle instead of dog
because i just changed it up here
the last thing i want to point out is
that
arrays also
you can check how many items are in
there if you look at the count and
that's going to return
the number of items in your array that
is sometimes useful when you want to use
a for loop with a range and you don't
know how many items are in the array you
can use this
array.count and get this number here but
just keep in mind that
although d has five items right here
the index of the last item is actually
only four because the first item is zero
it goes from zero one two three four
right even though there are five items
so just keep that in mind if you're
going to use this
array.count in conjunction with a for
loop or something like that
okay so that's where we're going to end
with arrays as you can see when you type
array dot there are a lot of different
functions
with arrays that you can do
what i've covered here in this lesson is
enough for you to use arrays and
leverage some of the main benefits of
arrays
as we go on and we're building apps
together you're going to be learning new
ways to use arrays but for now these are
the main things you need to know about
arrays in order to start using them
if you like this video please give this
video a thumbs up please subscribe for
more
hello welcome to lesson 17 of the learn
swift for beginners series
in this video we're going to go through
another collection type called the
dictionary
[Music]
in the previous lesson we went through
the array you can see here on the left
hand side and with an array we had a
collection of items where the order
mattered so you can see in this example
here in the swift programming language
guide six eggs is in spot number zero
whereas bananas is in index four
all right well a dictionary on this
right hand side here
is a collection type where order does
not matter
so in arrays we retrieve the item by
this index here and with the dictionary
because order doesn't matter we retrieve
these values using a key
so each value has an associated key when
you put it into the dictionary and you
need to pass it that same key and it's
going to return for you the value
now which collection type you use to
organize your data is going to depend on
obviously what sort of data you're
storing does order matter if it does
then the easy answer is to use an array
if it doesn't then maybe consider using
a dictionary so this is a good example
airports have these airport codes right
so each airport has an associated key
and that's a good point the keys should
actually be unique for each
value that you put in
another great example of when to use a
dictionary and this is the example that
i'm going to use in this video is
license plates so for example each
license plate is tied to a car
and each license plate is unique so the
key can be the license plate and the
value can be maybe a description of the
car or something like that
let's jump into xcode
in this new playground that i have here
and let me show you how to declare a new
dictionary and how to work with it
so why don't we declare
a variable here and let's call it car db
to represent car database
and let's looks like my playground has
crashed okay
and
what we're going to do here
is to declare a new dictionary so we use
the keyword dictionary and followed by
that we have these angle brackets where
inside we specify the data type of the
key followed by the data type of the
value so
for example let's pull
up that example again in here in this
dictionary the key would be a string
and the value would also be a string and
so
in between these two angle brackets we
would just put string comma string
and in order to create a
a new dictionary object we would just
end off with those two brackets and like
that we have an empty dictionary which
stores
key value pairs
and a key value pair is just a fancy
name for
one of these pairs of data
you know a key and a value
this dictionary stores key value pairs
where the key is a string and the value
is a string as well
now there is an easier way to write this
out without having to write so much
let me show you that second way
var
car db uh let's just say db2 is equal to
use the square brackets and then you
specify the data type of the key
followed by colon
and then the data type of the value and
again we have these two brackets here to
create a new
instance of that dictionary or new
dictionary object
and that's equivalent these two are the
same thing
doesn't this look very similar to
declaring a brand new array don't get
confused so for example
declaring a new string array would look
like
this would be my empty array
that is expecting to contain string
objects and this is an empty dictionary
that is expecting to contain key value
pairs where the key is string and value
a string as well
okay so we're going to stick with this
sort of declaration here so i'm just
going to go ahead delete this array
example that was just for demonstration
and delete that so now we just have card
db is an empty dictionary now how do i
assign something into the car database
dictionary well i would do car db
and then i would use these two
square brackets here and i would pass in
a key or i would specify a key rather
and this key would be a license plate
right so
you know this is going to be different
depending where you are in the world
but
let's just say it's like that
and then you assign the value into
the dictionary for that key so this
would be let's say
a blue
ferrari
now
this value blue ferrari is tied to
this key jsd238
how do i retrieve the value well
it's very simple i just give it the key
so if someone were to look up this
license plate let's say i print this out
like that
it would print out blue ferrari but
notice that it's wrapped in an optional
tag because
for example
if i passed in a key that doesn't exist
right let's pass in like asd 238 then
you can see there is no value for that
key all right so that's why it returns
nil so that's why when you access a
dictionary and you pass in a key it
returns to an optional
whatever data type that your value is
so when you pass in a key into your
dictionary to retrieve a value
just expect that it is an optional and
you may need to unwrap it and check if
it's nil before using it
okay so what if i wanted to
let's let's label this so
before we continue on this is declaring
a new
dictionary this is
adding
key value pairs
and this is
retrieving
data
and how do we update a value for a key
well it looks exactly like this
up here
so
you specify the key that you want to
update the value for
and here we can say that this guy now is
a red ferrari maybe it got a paint job
or something so
when you pass in this key from now on
you're going to get this new value
because this basically overwrote
whatever was there
before and in order to remove a value
remove a key value pair let's say
you can do something like this
you pass in the key
two three eight
and you assign it nil and actually that
is going to remove the key value pair
from your dictionary
now i'm going to show you how to iterate
over all of the key value pairs in your
dictionary so why don't we just add a
second key value pair in here
so that we have more than one item to
display
okay and this one can be a green
uh lamborghini
i think that's how you spell it i don't
have one so
i don't know for sure
and now let's iterate over it
wish i had one though
iterate over it we use a for loop
so we can say for
essentially for each key value pair
inside the dictionary do something
and the way you specify
this is you pass in
um we use what's basically called a
tuple okay and so you can think of a
tuple as a set of variables or a bunch
of variables so
we'll we're going to say
license
car
in
car db now the in keyword shouldn't be
new to you because you guys learned
about the for loop in a previous swift
lesson
so
um basically what should be new to you
though is this this is a tuple
so for each
tuple in
this dictionary we can do something
what's going to happen is it's going to
grab
each key value pair and the key is going
to be inside license
and the value is going to be car like
that so
now inside this for loop it's going to
iterate twice
and i'm going to find this key
or this license
inside this license variable and i'm
going to find the car
this string here blue ferrari or green
lamborghini inside this car variable
and it knows
even though there's no data type
associated with this tuple
because my dictionary is
string string for the key and the value
i'm going to simply print car
like that and you can see that
hmm it's just it's printing one
key value pair here it's printing one
car but i have two items
and the reason is because we've actually
removed
a key value pair with this statement
here so if i just comment this guy out
we have our two cars
and
it's red ferrari because we changed it
up here
now i can also print out the license i
can say
you know license
um
you know i can say something like
car
has a
license
like that
has a license
so that pretty much wraps up using a
dictionary and you're going to find that
it will come in handy along side arrays
in organizing your data so thanks for
watching if you like this video please
give it a thumbs up and please share it
with anyone you know who's also
interested in swift thanks for watching
i'll see you guys next time hey did you
join my free facebook community yet
that's where i hang out along with a ton
of other people learning ios just like
yourself i also post early access to all
of my videos inside that group before i
put them on youtube you can also get
help with any questions you're having
visit the link below click on the join
group button and i'll approve your
request right away alright so i'll see
you in there talk soon