2016-11-15 48 views
2

这是我目前如何声明我的变量。我通常会在需要时声明它们。宣布这些变量的适当位置在哪里?

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

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

+1

我会删除这些评论。他们不会添加任何通过阅读代码而不明显的新信息 – Alexander

回答

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