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 Build a Simple iPhone App with Swift Structs As Data Models Structs or Classes

Why does Pasan create an instance of the structure FactProvider?

Pasan creates an instance of the structure FactProvider which contains the array of facts, he then assigns that to a constant like this

let factProvider = FactProvider()

He then uses the constant factProvider in all the methods in the code instead of just using the original structure. Why is this?

Why can't I just use the original structure like this to access the array.

    override func viewDidLoad() {
        super.viewDidLoad()
        funFactLabel.text = FactProvider.facts[0]
    }

Why must you create an instance of it and use that to access the property (the array.facts)

This is what the code Pasan wrote looked like:

    override func viewDidLoad() {
        super.viewDidLoad()
        funFactLabel.text = factProvider.facts[0]
    }

1 Answer

Leo, the truth is, either way works, and with iOS being the development platform, they are both equally efficient. Although sometimes it can become confusing creating tens or maybe even hundreds of instances of different objects, it is important to remember just how natural of a practice this is, especially when programming in a object-oriented programming language. In this case, creating an instance of the FactProvider class does not necessarily need to be done in order to grab a fact, but in the context of the course and what Pasan is trying to convey, it is the best way he can present the object-oriented concept in a coherent way. I hope this helps.

If you have any further questions, feel free to ask!

Thanks a lot Landon!

You're very welcome, Leo!