iOS Development #9: Custom Types

iOS Development #9: Custom Types
Jan Zavrel
Jan Zavrel Follow June 28, 2021
Share:

If you’ve followed me so far, you should have three variables in your program, that hold your age, year of birth and name.

Let’s say I want to store this information about my daughter Julie as well. I could store three new values in three new variables named ageOfJulie, yearOfBirthOfJulie, and sexOfJulie:

var ageOfJulie = 7
var yearOfBirthOfJulie = 2014
var sexOfJulie = "female"

This approach is definitely possible, but it’s not very practical. With every new person I would have to create this set of variables that describes a specific person.

Luckily, there’s a better way. I can define my own custom type, a structure with these three properties:

  • age
  • yearOfBirth
  • sex
struct Person {
    var age: Int
    var yearOfBirth: Int
    var sex: String
}

Then I can create a new variable Julie of this custom type and initialize it with specific values:

var Julie: Person = Person(age: 7, yearOfBirth: 2014, sex: "female")

Let’s take a look at the code above in more details.

I defined the struct Person with three properties inside.

A property is just another name for variable or constant, which is inside a struct.

Below, I created a new variable Julie of type Person and I initialized it with three values, each for a specific property.

Now, I can easily access each property of the Julie struct like this:

Julie.age
Julie.yearOfBirth
Julie.sex

Creating a custom type

And as you can see, Playground will display a value of each property if you click on the box icon.

Next, I can create another variable for myself:

var Jan = Person(age: 40, yearOfBirth: 1981, sex: "male")

In this example, I deliberately omitted the specification of the type to demonstrate how Swift nicely infer it from the assigned value.

And these days, I can easily change my sex if I’m really into it:

Jan.sex = "female"

This will change the value of the sex property of the Jan person but it will leave Julie’s properties intact.

I hope you appreciate how we created logical structures with properties that are bound to the specific person so we can always access the right property based on the person’s name.

This approach is much easier to understand than using single variables for each value we want to store.

Follow me on Medium, Twitter, Facebook and YouTube.

Share:
Jan Zavrel
Written by

Jan Zavrel Follow

Developer, Author, Teacher, Evernote Certified Consultant.