Accessing Variables outside of a function in swift

10,629

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

Share:
10,629
Learnin
Author by

Learnin

Updated on June 04, 2022

Comments

  • Learnin
    Learnin almost 2 years

    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.
      }
    }
    
  • Learnin
    Learnin over 9 years
    Thanks! This worked perfectly! For any one else reading this, when using this method I think you also need to implicitly unwrap the variables when using them, otherwise you get errors. At least that fixed the error signs for me, e.g typing println(coord!.latitude), as opposed to println(coord.latitude)
  • Learnin
    Learnin over 9 years
    Thanks! The other method is more intuitive for me, at least when dealing with the single variable, but this helped to! Quick question, how would I go about accessing the info from another file? Say another viewController?
  • Learnin
    Learnin over 9 years
    Also! Just making sure for future reference, how would I go about making the variable accessable from another file?
  • dcgoss
    dcgoss over 9 years
    @Sholto You're welcome! As for making properties of ViewController accessible from another file, you would need to make an instance of the class in that file, which will inherit all of the instance variables and methods from the original ViewController class. This is accomplished like this : class TestClass{ var instanceOfClass = ViewController(). Then you can access properties of that instance with dot notation like so: instanceOfClass.coord retrieves the variable coord from the instance of your class (instanceofClass)
  • dcgoss
    dcgoss over 9 years
    @Sholto Also, good catch on implicit unwrapping! As you said, this is required for wrapped optional variables. However, if you do not want to do this you can declare it as an implicitly unwrapped optional by removing the ? and replacing it with a !. Then, you won't have to use the ! when using the variable because it's already unwrapped in the declaration
  • Learnin
    Learnin over 9 years
    I ran into the problem that swift at least at the moment says viewcontrollers arent constructible with just (). I've looked around and one thing that seems to work is var instance1 = self.storyboard.instantiateViewControllerWithIdentifier("Log‌​inPage") as ViewController2 Problem is, when i try to access the variables from inside this instance, they come out as nil (Or at least dont seem to have value?), any suggestions?
  • Learnin
    Learnin over 9 years
    Wait, did a quick check. If I create a variable like r = 3 then i can access it fine, but an array which I've added objects to doesnt seem to work, it may be I'm messing up creating the array!
  • Learnin
    Learnin over 9 years
    Yeah, it seems like for this created instance of the viewcontroller2 a created array is empty, any idea how to work around it? Say by referencing the same viewController2?
  • xhinoda
    xhinoda almost 7 years
    maybe you can declare like this: public var locationObj : CLLocation?