简体   繁体   中英

How to make value in func to global constant in Swift

How do I go about setting the long and latitude value (both which display a when app runs) to a global constant? The values are currently

String(format: "4.4f", latestLocation.coordinate.latitude) 

and

String(format: "4.4f", latestLocation.coordinate.longitude)

I want to make these a global constant like userlatitude and userlongitude which can be accessed outside the function. Do I have to return someHope that makes sense.

func locationManager(manager: CLLocationManager!,
    didUpdateLocations locations: [AnyObject]!)
{
    var latestLocation = locations.last as! CLLocation

    latitude.text = String(format: "%.4f",
        latestLocation.coordinate.latitude)
    longitude.text = String(format: "%.4f",
        latestLocation.coordinate.longitude)
}

This way you can store Locations to NSUserDefaults :

//First Convert it to NSNumber.
let lat : NSNumber = NSNumber(double: Location.latitude)
let lng : NSNumber = NSNumber(double: Location.longitude)

//Store it into Dictionary
let locationDict = ["lat": lat, "lng": lng]

//Store that Dictionary into NSUserDefaults
NSUserDefaults.standardUserDefaults().setObject(locationDict, forKey: "Location")

After that you can access it this way anywhere you want:

//Access that stored Values
let userLoc = NSUserDefaults.standardUserDefaults().objectForKey("Location") as! [String : NSNumber]

//Get user location from that Dictionary
let userLat = userLoc["lat"]
let userLng = userLoc["lng"]

var Annotation = MKPointAnnotation()

Annotation.coordinate.latitude = userLat as! CLLocationDegrees  //Convert NSNumber to CLLocationDegrees
Annotation.coordinate.longitude = userLng as! CLLocationDegrees //Convert NSNumber to CLLocationDegrees
  1. Define your Variable Below of import statement. Something Like,

     import UIKit let latitude = 4.0 // Do Stuff - This Variable access in Any class. Thanx Swift.... 
  2. Another solution is put your value in .plist/NSUser Default and access in every class(Where should you wish to use) using appropriate key.

One solution could be that you store the values as NSUserDefaults, which gives you access to the values when you need it. try this link for more information http://www.codingexplorer.com/nsuserdefaults-a-swift-introduction/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM