Muhammad Harits Syaifulloh

Friday, October 28, 2016

Swift 3 - Classes And Objects

Classes and Objects are fundamental to all object-oriented programming languages, of which Swift is one. A Class is simply a blueprint in code that allows you to create multiple instances of itself and these instances are called Objects. So by using one blueprint you can create multiple items called Objects. Let's see how this works in practice by following along inside of our playground.

Now let's create a class with the keyword class and this is a word you're going to see a lot, and this class are called myClass. Now unlike a function, there are no arguments parameters to pass over. In this part of the class there are places we can do that and I will cover that but we just want curly braces.

Now a class is a blueprint, it's a container and it holds things like properties, variables, functions, structures, enumerations and lots of other things. It can hold pretty much everything you can think of in programming. So the next we're going to do is fill the myClass class with some variables, functions, etc.

So we have filled myClass and we can see that function getSwiftVersion will return an integer value that's swiftVersion. And we can see self and it's the better way to write it, self there refers to the class of myClass so it's looking at itself and saying okay what stuff do I have. Then we assign mySwift with myClass() and call function getSwiftVersion in the myClass and it we have the value on the right-hand side of our playground.

Now let's say our myClass has a different Swift version each time were created and we want to pass over the swiftVersion. Well rather than going through the pfaff of changing that variable each time we can use what's called an initializer in the class. And an initializer is the methods that gets called whenever the class is instantiated or it's used to make an object.

So whenever you get an error saying "Missing arguments" what's asking for is the stuff in the init function, so just to recap a Class is a blueprint that allows you to create objects. Now let's try again:

So look at how a class allows us to create multiple instances of itself and multiple different kinds of cards. Classes and objects are one of the fundamental parts of object-oriented programming and you can't go wrong by knowing too much about them they are that fundamental.

Alright guys, that's all about Classes And Objects. I hope it will be easy to learn and to understand and if you have any question just leave some comments below. Thank you very much for visit my blog and see you at the next tutorial.

No comments:

Post a Comment