ConnorB ConnorB - 20 days ago 7
Swift Question

Where is the proper place to declare these variables?

This is how I currently declare my variables. I usually declare them as I need them.

//Instantiate Map
let map = MKMapView()
map.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height)

//Edit Properties
map.mapType = MKMapType.standard
map.isZoomEnabled = true
map.isScrollEnabled = true

//Center map in view
map.center = view.center

//Get coordinates from App Delegate
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let coordinates = appDelegate.coordinates

//Set map location
let radius = 1000.0
let region = MKCoordinateRegionMakeWithDistance(coordinates, radius * 2.0, radius * 2.0)
map.setRegion(region, animated: true)


Would it be better practice to declare those variables at the top? I find it a lot easier to read if I declare them as I use them.

Answer

What you're doing is excellent. Keep in mind that let variables will be optimized away in any case; no storage will actually be set aside. In other words, no matter where you say let in

let radius = 1000.0
let region = MKCoordinateRegionMakeWithDistance(coordinates, radius * 2.0, radius * 2.0)
map.setRegion(region, animated: true)

the compiler will optimize it as if you had said

map.setRegion(MKCoordinateRegionMakeWithDistance(coordinates, 1000 * 2.0, 1000 * 2.0), animated: true)
Comments