Open the demo from the previous playground. You’ll be continuing from where you last left off. Objects are everywhere in Swift. In fact, you’ve already been using objects since the very beginning. All those variables are instances of objects.
For example, in the last demo, you created an integer called myInt. Type out the name, and add a period at the end of it.
myInt.
You’ll see a list of all the properties and methods you can access on the object. The properties are in light blue. Note, a property is pretty much a variable. It represents a single value. The darker blue represent a method. That is, this code that you can run on it.
You don’t need a variable as well. You can access these off an integer itself.
10.
Strings also have lots of useful methods. First, let’s create a full name variable that contains both the first name and last name.
var fullName = firstName + " " + lastName
This is another way to create a string. We are literally adding the firstName and lastName together. If you don’t add the space in between them, your names would run into each other.
Now we’ll print out the fullName, but this time, we will lowercase it.
print(fullName.lowercased())
Run your code. And look at that. Your name is lowercased. Check out all the other methods to see what you can do.
Now to define an object. Earlier, you created a traffic light. You may have a program where you need to print out lots of traffic lights. Create the following class:
class TrafficLight {
func display() {
print("🟧🟧🟧")
print("🟧🔴🟧")
print("🟧🟡🟧")
print("🟧🟢🟧")
print("🟧🟧🟧")
}
}
This defines a TrafficLight class with a display method. Calling display(), prints out the light. Now try creating an instance of the light and calling the display method. Pause the video and try it out. Okay, here we go. First I’m going to create a light variable that creates a new instance.
var light = TrafficLight();
Now I just call the display method on the traffic light.
light.display()
I can actually call it multiple times.
light.display()
light.display()
Now run your code. And look at that, traffic lights for days!