Working with Objects
Most modern programming languages use objects. Objects are a way to organize code. Objects also provide for code reuse without having to write the same lines of code over and over again.
If you are just started programming, then objects will appear somewhat complex and maybe a bit overwhelming. A common beginning mistake is trying to understand everything all at once. For this course, focus on the high level concepts. In later courses, you’ll actually get into the weeds. This course is just introducing you to the garden.
Creating objects
Objects do a few things, but one critical thing is it allows you to group data, and pass that data around as a singular object. In the previous demo, you created a firstName and lastName variable. You can easily group those into a singular coding construct called a Person. You would define it like so:
class Person {
var firstName = ""
var lastName = ""
}
This bit of code defines a class. A class is a template. When playing a role-playing game, you often get to pick your character class. This could be a fighter, wizard, or thief. The class defines what it can do, and then you create instances of it. For example, there is one wizard class but Gandalf, Merlin, and Dr. Strange are individual instances of that class.
To create some new people, you write the following code:
var katie = Person()
var sam = Person()
var jeremy = Person()
You can then assign their first name and last name by using a period followed by the variable name. For example:
jeremy.firstName = "Jeremy"
jeremy.lastName = "Patterson"
Calling methods
Objects don’t just contain data. They can also act on that data. You define something known as method. A method is just a short block of code that can run on demand. Often times, these are called functions as well. For example, you can write a method to print out the full name.
class Person {
var firstName = ""
var lastName = ""
func printFullName() {
print("\(firstName) \(lastName)")
}
}
The method is defined with the func keyword. In this case, the method simply prints out two variables together. You call it like the following:
katie.printFullName()
Methods can also take in values and return values. Later in this course, you’ll define a few methods, but for the most part, you’ll just be working with objects. That said, you’ll quickly discover that objects are key for leveraging both Swift and iOS.