-4

Say I have a instance of a class let geocoder = CLGeocoder().

I can now call geocodeAddressString, a method of the CLGeocoder class:

geocoder.geocodeAddressString(myObject["Location"] as! String, completionHandler: {
    (placemarks, error) -> Void in
    ...
}

Though, why can't I directly do the following?

// I haven't instantiated the `CLGeocoder` class this time
CLGeocoder.geocoder.geocodeAddressString(myObject["Location"] as! String, completionHandler: { (placemarks, error) -> Void in
    ...
})

For example, I can do:

// I don't instantiate the UIView class here
UIView.animateWithDuration(0.4, animations: {
    () in
    ...
}

When do I have to instantiate a class and when I shouldn't?

  • 1
    This is pretty basic object oriented programming. Just look at the documentation and see how it's implemented. For more reading, perhaps see this: [What is the difference between class and instance methods?](http://stackoverflow.com/q/1053592/2792531) – nhgrif Oct 31 '15 at 14:58

1 Answers1

2

In your second example, the function "animateWithDuration()" is what we call a static method, meaning you can call it without instantiating an instance of that class.

In your first example, since the instance you called "geocoder" isn't actually a variable within the class, you cannot call it statically.

Generally speaking, if you want to use static methods, you do not have to instantiate, however if you want to use non-static ones, you must use a instance (instantiated) version of that class.

This is the basis for object-oriented programming.

Reedie
  • 189
  • 1
  • 1
  • 10
  • Thanks Mapboy! Is `geocodeAddressString` a method of the class `CLGeocoder `, right? – Cesare Oct 31 '15 at 14:59
  • From what I can tell, yes. Since it appears to not be a static method, you would have to call it from an instance of that class. – Reedie Oct 31 '15 at 15:00