Structs in Swift for Newbies
In this article I will be discussing Structs
in Swift.
Classes and structures are general-purpose, flexible constructs that become the building blocks of your program’s code. You define properties and methods to add functionality to your classes and structures by using exactly the same syntax as for constants, variables, and functions.
— Apple Documentation
In simple terms, a struct
is like a custom data type
which provides storage of data using properties
with extended functionality using methods.
Let’s take a look at how a struct’s syntax
looks like.
As you see, we define it with the struct
followed by a name of the struct
then open braces
then close braces
.
Inside the braces
is where your properties
go. Properties
are like attributes
of the struct
.
For example we could have a User
struct where it’s properties
are username
, email
, and name
.
I think the best way to show what structs
are is to start using them.
Open playground
.
Let’s use the User
example.
Now that we have defined our struct
with properties
we can now create an instance
of it.
To read a property
you simply do this:
Value Type
It’s important to know the difference between value and reference types.
Structs are value type, meaning it’s value is copied when assigned or passed.
Hopefully this example will make sense.
Let’s create another instance of User
, call it user2
.
Create a variable user3
and make it equal to user2
.
Now let’s manipulate user3
’s username
.
To see what I’m talking about let’s print out both usernames of user2
and user3
.
As you see we copied user2
to user3
, then we changed user2
’s username
.
When we print, you can see that user3
does not change.
If you don’t understand my example take a look at Apple’s.
Functions inside structs
We can also have functions inside structs like so:
To call this function we use person
variable.
That’s the gist.
Thanks for checking out Structs!
Any suggestions on future articles or comments feel free to let me know!
Most likely I will be covering Classes next 😊 .