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 Object-Oriented Swift Classes in Swift Classes with Custom Types

Chase Maddox
PLUS
Chase Maddox
Courses Plus Student 5,461 Points

Confusion on Init Method

Hi,

I'm confused as to how the init() method works when there are multiple arguments and connecting the previous struct into the code. I tried reading through the Swift documentation on Initialization that Apple provides, but that was more overwhelming than helpful. Can you help me understand what I'm doing wrong in my code and not understanding?

Thanks, Chase

objects.swift
struct Location {
  let latitude: Double
  let longitude: Double
}

class Business {
  let name: String
  let location: Location

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

let someBusiness = Business(name: "Chik-fil-A", latitude: 10.0, longitude: 13.0)

1 Answer

Michael Hulet
Michael Hulet
47,913 Points

Initializers are special methods that run only whenever you make a new instance of an object, but at their core, they're just methods. Methods can specify what they take as parameters, and then do something with what it's given. The initializer you made for your Business class says that it takes a String called name, and a Location struct called location. However, when you call it, you're giving it a String called name, a Double called latitude, and another Double called longitude. It's expecting a Location object, not 2 Doubles that aren't tied to anything at all, so you need to pass it one, like this:

//Notice how we're making a Location object and passing that to the Business initializer
let someBusiness = Business(name: "Something", location: Location(latitude: 100, longitude: 100))

Also, in the body of your initializer, you're creating a new Location object from latitude and longitude parameters that don't exist. Instead, it's safe to just take the Location object that the Business initializer is given and assign it directly to self.location

Chase Maddox
Chase Maddox
Courses Plus Student 5,461 Points

Thanks so much for the clarification and help Michael! I see what I did, and definitely need some more practice.

Michael Hulet
Michael Hulet
47,913 Points

No problem! I'm glad I could help. You're definitely on the road to being a great Swift developer!