Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Swift Enums and Structs Structs and their Methods Initializers

Where the Structs are used in application in realtime example ?

i want to know more about structs and usage in real time app

2 Answers

Pasan Premaratne
STAFF
Pasan Premaratne
Treehouse Teacher

@kantanandus

There are a couple differences between structs and classes, one of which, as @ezfe mentioned is that a struct is a value type (the actual value is passed rather than a pointer). Structs also cannot inherit from other structs/classes where as a class can. Usage in an app basically comes down to this:

What do you want to model? Value types, i.e. structs, are inert. They are best used to store data and have methods that perform computations on the data. This data can be modified by a single owner - the struct instance. Swift hasn't been around long enough for best practices to emerge but in my code, I've been implementing all my models as structs wherever possible. This wayI know that multiple owners cannot change the same instance.

In the iOS courses that are included in the swift track, we try to use structs for the model layer unless we need inheritance or any of the other complexities that classes offer

Here's a good overall article on the usefulness of structs and value types

@pasan premarathen

Thanks you so much for the detailed view , I Got some more knowledge from you like the usage of structs .

The main difference between Structs and Classes is that a struct isn't passed as a pointer. This creates different use cases.

For example, a class might be the Player class in a video game, because you want to have the same player everywhere (passing pointers). The Swift Book uses the following example

struct Resolution {
    var width = 0
    var height = 0
}

Excerpt From: Apple Inc. β€œThe Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l

In the example, Resolution is more complex than an Enum, but it doesn't need to be its own Class.

@Ezekiel Elin , Thank you so much