Accessing Variables outside of a function in swift

老子叫甜甜 提交于 2019-12-02 01:41:05

If I understand you correctly, I think the best option would be to make it an instance variable, as you said. This would be done by declaring it outside of the function with your other instance variables at the top of your class (the asterisks are used to show you what I added):

 class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {

    var locationManager: CLLocationManager!
    var seenError : Bool = false
    var theSpan: MKCoordinateSpan = MKCoordinateSpanMake(0.1, 0.1)
    var locationStatus : NSString = "Not Started"

    var initialLoc:Int = 1

// Declare coordinate variable
 ***var coord: CLLocationCoordinate2D?***

The question mark declares the variable as an optional, so you don't have to immediately assign a value to it.
Then, you assign the locationObj.coordinate value to coord in your locationManager function, however since you already declared the coord variable outside your function as an instance variable you can remove the var in var coord = locationObj.coordinate :

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {

        var locationArray = locations as NSArray
        var locationObj = locationArray.lastObject as CLLocation

        //Assign value to coord variable
     ***coord = locationObj.coordinate***

        if initialLoc == 1 {
            var Region:MKCoordinateRegion = MKCoordinateRegionMake(coord, theSpan)
            self.Map.setRegion(Region, animated:true)
            initialLoc = 0
        }

Then you can use the variable normally in the rest of your function, in addition to any other function in the class (like a global variable).
Best of luck!
P.S. Learn how to do this well, as it is a method used all the time when working with functions and variables

At the point where you read the location into a local variable, instead read it into an instance variable. So instead of:

var locationObj = locationArray.lastObject as CLLocation

use

self.locationObj = locationArray.lastObject as CLLocation

and declare

var locationObj : CLLocation?

in your ViewController. Then you can access locationObj with 'dot' notation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!