-1

I am getting about 10 warning signs letting me know that i should consider using let in place of var in these situations. Let is a constant, where var changes. In this case, would changing to let be the proper decision?

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    var latitude: CLLocationDegrees = 50.0358

    var longitute: CLLocationDegrees = 19.1783

    var latDelta: CLLocationDegrees = 0.5

    var longDelta: CLLocationDegrees = 0.5

    var span: MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta)

    var location: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitute)

    var region: MKCoordinateRegion = MKCoordinateRegionMake(location, span)

    mapView.setRegion(region, animated: true)

    var annotation = MKPointAnnotation()

    annotation.coordinate = location

    annotation.title = "Auschwiz"

    annotation.subtitle = "German Nazi concentration camp."

    mapView.addAnnotation(annotation)

    var uilpgr = UILongPressGestureRecognizer(target: self, action: "action:")

    uilpgr.minimumPressDuration = 2

    mapView.addGestureRecognizer(uilpgr)
Caleb Bach
  • 162
  • 11
  • 2
    The Swift team advises to use constants by default and use variables only if you really really need to mutate this object in your code logic. So by default, use `let` everywhere unless you really can't make it work and need a variable. tl;dr The compiler is right. – Eric Aya Oct 14 '15 at 20:04

2 Answers2

1

In this case the choice between var and let is more a matter of readability.

When people reading your code see var they expect that the value of that variable will change at some point. Analogously when they see let they know the variable can't change.

This separation is strong in the mind of swift programmers. Using var in a variable that is not meant to change can be misleading. Your program works just fine but it imposes a certain confusion to a reader, which is why you get a warning.

I tend to define local variables with let initially and later on change to var if needed.

Edman
  • 5,335
  • 29
  • 32
1

Yes use let in this case. You basically have to ask yourself, will these values latitude, longitude, latDelta, etc., ever change? If the answer is no, which by looking at your code it's pretty obvious they won't ever change, then use let.

This applies to every situation, it doesn't matter if your defining values for map objects, UI objects, or any other objects within the swift language.

Lastly, not only does differentiating between let and var lend itself to more readability by other programmers, from a pure development point of view, immutables or let values, can be subject to optimizations by the compiler.

Yonny
  • 404
  • 7
  • 14