We’ve created models of real-life objects using instances and now let’s find out how to customize them. Since instances of a struct can have different property values, we should know how to access these values. In Swift, we use dot syntax to do just that:
instance.property
This might look familiar from other exercises like trying to find .count
of a collection type. That’s because .count
is also a property, that’s right we’ve used properties before!
Let’s turn back to our trusty Dog
structure:
struct Dog { var age = 0 var isGood = true } var bucket = Dog()
Notice that we added a Dog
instance, bucket
who still has the structure’s default properties and values. To check bucket
‘s properties, we use dot syntax as mentioned earlier:
print(bucket.age) // Prints: 0 print(bucket.isGood) // Prints: true
Awesome, we were able to access property values! We can also reassign properties using the assignment operator (=
). Suppose bucket
is 7 years old and he is being a bad boy, we can reassign the values, like so:
bucket.age = 7 bucket.isGood = false
Instructions
Print out the value of myFavBook
‘s .pages
property.
It turns out that myFavBook
actually has 640 pages! Change the value of .pages
to 640
.
Then, print out the value of myFavBook
‘s .pages
property.
While we’re at it, let’s also give myFavBook
an actual title.
Assign myFavBook.title
a String
value that contains the title of your favorite book.
Afterward, print out the value of myFavBook.title
.