ConnorB
ConnorB

Reputation: 406

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.

Upvotes: 2

Views: 35

Answers (2)

Alexander
Alexander

Reputation: 63399

That looks like some pretty good looking code. I may tweak as few things:

let map = MKMapView()
// 1) use init(origin:size:) instead:
map.frame = CGRect(origin: CGPoint(), size: view.frame.size)
map.mapType = .standard // 2) "MKMapType" can be inferred by the compiler
map.isZoomEnabled = true
map.isScrollEnabled = true
map.center = view.center

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let coordinates = appDelegate.coordinates
let radius = 1000.0
let region = MKCoordinateRegionMakeWithDistance(coordinates, radius * 2.0, radius * 2.0)
map.setRegion(region, animated: true)

Upvotes: 0

matt
matt

Reputation: 536027

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)

Upvotes: 1

Related Questions