Accessing Variables outside of a function in swift

2019-02-25 18:10发布

Im getting coordinates from , but I'd like to be able to use them outside the Location Manager Function. Is it possible to make them instance variables? If so, could someone give me some example code for that? In the code below I print within the func and it works, but I'd like to be able to, for example print outside it, and otherwise use the coordinates. Perhaps as a global variable? How would i code that? I cant quite make it out from the documentation.

import UIKit
import CoreLocation
import MapKit

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

  override func viewDidLoad() {
    super.viewDidLoad()

    locationManager = CLLocationManager()
    locationManager.requestAlwaysAuthorization()
    locationManager.delegate = self
    var initialLoc:Int = 1
    // Do any additional setup after loading the view, typically from a nib.
  }

  @IBOutlet weak var Map: MKMapView!
  @IBAction func Here(sender: AnyObject) {       
    initLocationManager()
  }

  func initLocationManager() {
    seenError = false
    locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.startUpdatingLocation()
    Map.showsUserLocation = true
  }

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

    var locationArray = locations as NSArray
    var locationObj = locationArray.lastObject as CLLocation
    var coord = locationObj.coordinate
    if initialLoc == 1 {
        var Region:MKCoordinateRegion = MKCoordinateRegionMake(coord, theSpan)
        self.Map.setRegion(Region, animated:true)
        initialLoc = 0
    }
    println(coord.latitude)
    println(coord.longitude)
  }

  // Location Manager Delegate stuff
  // If failed
  func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
    locationManager.stopUpdatingLocation()
    if (error) {
        if (seenError == false) {
            seenError = true
            print(error)
        }
     }
  }

  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
}

2条回答
放我归山
2楼-- · 2019-02-25 19:02

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

查看更多
等我变得足够好
3楼-- · 2019-02-25 19:02

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.

查看更多
登录 后发表回答