Previous episode: 37. Challenge: Functions
Next episode: 39. Challenge: Structures
Get immediate access to this and 4,000+ other videos and books.
Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and
4,000+ professional videos in a single subscription, it's simply the best investment you can make in
your development career.
In this exercise, we'll begin our tour of structures in Swift. You usually hear structures called struct. Structs, like tuples, allow you to group a set of related data together. For example, maybe you wanna store a person's first name, their last name, and their favorite color into a single unit. In a struct, those bits of data are called properties, and they represent what a structure has. Now, unlike tuples, structures can also contain methods. And again, methods represent what a structure does. Remember, methods are just like the function you've been learning about so far, but the difference is that methods belong to a named type, like a struct. So when you were building the bulls-eye app, you used structs to build up the views in the app. But structs aren't just for defining views, you can use them to model all sorts of data. You're actually very familiar with some other structures, many of the built-in Swift types you've been using throughout this course are structures. So ints, doubles, bools, strings, arrays, dictionaries, surprise! They're all structures. Now being able to define your own structures will come in handy. So to demonstrate, you'll start by turning your student tuple into a structure. At the top of the playground page, you'll find the type alias we use to represent a student. Now I've comment this out because we're going to create a struct with the same name. To start, use a keyword struct, and then the types name, student. So take note of the capital S at the start of Student, and that's a Swift convention to start all type names like this. Now, to turn these tuples values into properties. Now properties are just constants or variables that belong to a type, so you define them in a similar way. You start with let or var and fall up the names with explicit typing, okay? So we don't expect a student's name to change, so that should be a constant. But a student's grade might change, or they might decide to need a pet iguana, so those properties should be variables. And note that I've made the pet property an optional string. When you define a structure, you're making something like a blueprint. You haven't created any student in particular yet, you've just laid out a common way to describe all students. Now you could give these properties values right here, but in this case, we want to set those properties to different values for each student. Now to actually create a student, start typing up the first few letters of Student, and then hit return for auto-complete. Then, type and opening parenthesis and use auto-complete again. What you're seeing here is the initializer for the student struct. Structs automatically generate an initializer like this for you. Now you can set the values for those three properties via the initializer. So what you've created here is known as a student instance or an instance of student. Now you can store that instance in a new variable or constant just like you'd expect. So remember that a struct is like a blueprint, so you can make as many students as you want, and I'll make two more. So this student struct has things, but it doesn't do anything yet. And to fix that, we can add a method. So writing a method is just like writing a function, except you do it inside of a type definition. So I'll write a method to find out if a student is passing, just like the function from earlier in this part. Now because you're inside the student definition, you have access to its properties, that means you don't need to pass in the grade property to use it, you just need the lowest pass parameter this time, and you can set a default value exactly the same way you've done before. Now, I want this method to return a Boolean. And inside of the method body, I'm going to write the expression to compare the grade for a student to the lowest passing grade. So remember, if the body of a function or method is only one line, the result is returned implicitly, so there's no need to use the return keyword here. So now I can find out if a student is passing. Start with one of the students you created, followed by a dot, and take a look at the auto-complete list. And you should see all of the available properties methods for the student structure. I just wanna find out if Chris has passed, so I'll choose the getPassStatus method. Because there's a default value set for lowest pass, I have the option to call this method without arguments. Okay, this guy needs some extra credit or something to help that grade, now I can take care of that by adding one more method that adds 10 bonus points to the grade property. So you'll see an error at this point. When a struct's method changes or mutates a property of struct, you need to explicitly say that it can do so, and you can do that with the mutating keyword, just add it right in front of func, and then the error goes away. So now, I can call earn extra credit on Chris. Oh, except that I can't because the grade property is a variable but Chris is a constant, so I need to change Chris to a variable in order to change any of its properties. And now earn extra credit can run. And if I get the pass status again, yay, he's passing finally! Now I mentioned in the introduction to this part that structures are really designed for representing values. A struct is what's called a value type. To illustrate what that means in practice, we'll make an evil clone of one of our students. So let me start with the new constant. So then I'll assign the real student to the new variable, so at this point, they'll have the exact same values for their name, grade and pet. So I'm gonna try to change a variable properties on the evil version. Oh, okay, that doesn't work. So even though both grade and pet are variables, evilCatie isn't. To be able to change any of the values, I need to change this let to var. So now I can change even more properties. So now that those properties can change, if you show the values of both Catie and evilCatie, they no longer match. So, is that what you expected, or in your mind, if you were to assign a student to two different variables, would you expect them to always keep their properties in sync? Now, both ways of thinking are valid. But when dealing with value types, which structures are, all the variables you assign will be independent. So if you assign an instance of a structure to a constant or a variable, you're actually creating entirely new structure with the same values as the original. Does that make your head spin? That's okay, you'll get some practice with value types in the next challenge, and we'll also cover them in depth in a later course, programming in Swift, functions and types. And after this next challenge, you're going to learn about classes. Classes are referenced types, and they work a little differently. So maybe you'll decide that student should be a class instead of a struct, but for now, this will do.
All videos. All books.
One low price.
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.