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 What is an Instance?

Josh Schlabach
Josh Schlabach
1,771 Points

Still confused about instances

After watching this video, I got a good idea of what instances are, but I'm still confused. Can someone give me an example?

3 Answers

Here is an example where we create a Car struct and then below that we create 2 instances of the Car struct, car1 and car2. car1.toString() produces "2005 Jeep Wrangler" and car2.toString() produces "2004 Nissan Altima". Both car1 and car2 are cars but are separate instances of the Car struct.

struct Car {
    var make : String
    var model : String
    var year : Int

    func toString() -> String {
        return "\(self.year) \(self.make) \(self.model)"
    }
}

var car1 = Car(make: "Jeep", model: "Wrangler", year: 2005)
car1.toString()
var car2 = Car(make: "Nissan", model: "Altima", year: 2004)
car2.toString()

To re-iterate the car example, the struct would be the design for the car (for example; the design for the 2015 Toyota Camry), while an instance would be the particular 2015 Toyota Camry, that I bought.

My Camry may be the exact same model and year as compared to my neighbours Camry, but it might have some differences such as colour and optional features (it could even be the exact same, but one is mine and the other is my neighbour's), therefore they are two different instances of the same struct.

JIHOON JUNG
JIHOON JUNG
10,927 Points

To me, instance is a design of products I will make

Like Car explained by Bryson Armstrong, before we create an actual car, we design it first what to name, when to create, etc.

Once you've done with designing, then you will make a lot of cars based on your design.

That's my understanding :D Hope it will helps