简体   繁体   English

如何在Swift中的func中为全局常量创造价值

[英]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. 我想让这些成为全局常量,例如可以在函数外部访问的userlatitudeuserlongitude 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 : 这样,您可以将Locations存储到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. 在import语句下面定义您的Variable。 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. 另一种解决方案是将您的值放在.plist/NSUser Default中,并使用适当的密钥在每个类(您希望在何处使用)中进行访问。

One solution could be that you store the values as NSUserDefaults, which gives you access to the values when you need it. 一种解决方案是将值存储为NSUserDefaults,这使您可以在需要时访问值。 try this link for more information http://www.codingexplorer.com/nsuserdefaults-a-swift-introduction/ 尝试此链接以获取更多信息http://www.codingexplorer.com/nsuserdefaults-a-swift-introduction/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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