声明这些变量的适当位置在哪里?

时间:2016-11-15 02:23:19

标签: swift

这就是我目前声明变量的方式。我通常在需要时声明它们。

        //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)

在顶部声明这些变量会更好吗?如果我在使用它们时声明它们,我发现它更容易阅读。

2 个答案:

答案 0 :(得分:1)

你所做的很棒。请记住,let变量在任何情况下都会被优化掉;实际上没有存储空间。换句话说,无论你在哪里说let

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

编译器会像你说的那样优化它

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

答案 1 :(得分:0)

这看起来像一些漂亮的代码。我可能会调整一些事情:

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)