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


Carson Carbery
Carson Carbery
9,876 Points

Fun Facts app. Why use structs?

Hi all, I'm new to OOP and really trying to understand it correctly so appreciate any input on this. I kind of get the statements made in the videos, but am not seeing the benefits in the examples and exercises. For example in the fun facts app we use a Struct:

struct FactModel { let facts = [ "Ants stretch when they wake up in the morning.", "Ostriches can run faster than horses.", "Olympic gold medals are actually made mostly of silver." ]

func getRandomFact() ->String { let randomNumber = GKRandomSource.sharedRandom().nextIntWithUpperBound(facts.count) return facts[randomNumber] }

which contains an array of facts along with a method. So why not just use an array and function (which would mean you wouldn't have to go through the struct to get to the information in the array)? Or is the concept basically just to keep data encapsulated together with its related functions (methods)?

1 Answer

Hi Carson, the reason we create a Struct is to store both the array and method(function) inside a single object, the Struct.

That way we can call the method(get random) and return it's values(the array of facts).

funFactLabel.text = factModel.getRandomFact()

It makes the process a bit easier to read, and understand as well.