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

Creating an instance of a class in Swift 2.0 Challenge

I'm struggling to create and instance of a class in the challenge for Swift 2.0. Within the initialiser for the class I have included a struct but I'm not sure if I have to reference the values within this when creating an instance of the class.

In the editor you've been provided with a struct named Location that models a coordinate point using longitude and latitude values.

For this task we want to create a class named Business. The class contains two constant stored properties: name of type String and location of type Location.

In the initializer method pass in a name and an instance of Location to set up the instance of Business. Using this initializer, create an instance and assign it to a constant named someBusiness.

struct Location {
    let latitude: Double
    let longitude: Double
}
// This is my code:

class Business {
  let name: String
  let location: Location

  init(name: String, location: Location) {
    self.name = name
    self.location = location
  }
}

let someBusiness = Business(name: "Trump", location: )

2 Answers

Hi Ian,

You almost got it! Here's what you tried in your code:

let someBusiness = Business(name: "Trump", location: )

You have an argument for name ("Trump"), but you are unable to create an instance of the class because your are still missing an argument for location. You need to provide both arguments to successfully create an instance of the class.

There are two ways to solve this. The first way you can solve this is by creating an instance of the struct before you try to create an instance of the class, then pass the instance of the struct as an argument for location. For example, you could first write:

let someLocation = Location(latitude: 10.00, longitude: 20.00)

Then pass someLocation as an argument when you create an instance of the class

let someBusiness = Business(name: "test", location: someLocation)

The other way to solve this is by creating an instance of Location when you create an instance of the class, like so:

let someBusiness = Business(name: "test", location: Location(latitude: 10.00, longitude: 20.00))

Hope this helps!

Ahhhhh that makes a lot of sense!

Many thanks for your help!! :)