如何在Swift中使func中的值成为全局常量

时间:2015-06-23 09:12:00

标签: ios iphone swift

如何设置长度和纬度值(两者都显示app运行时)到全局常量?这些值目前是

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

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

我想让这些像userlatitudeuserlongitude这样的全局常量可以在函数外部访问。我是否必须返回一些有意义的希望。

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)
}

3 个答案:

答案 0 :(得分:1)

这样您就可以将地点存储到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")

之后,您可以通过这种方式访问​​它:

//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 :(得分:0)

  1. 定义您的变量以下导入语句。喜欢的东西,

    import UIKit
    
    let latitude = 4.0
    
    // Do Stuff - This Variable access in Any class. Thanx Swift....
    
  2. 另一个解决方案是使用适当的密钥将您的值放在.plist/NSUser默认值并访问每个类(您希望在何处使用)。

答案 2 :(得分:0)

一种解决方案可能是将值存储为NSUserDefaults,这样您就可以在需要时访问这些值。请尝试此链接以获取更多信息http://www.codingexplorer.com/nsuserdefaults-a-swift-introduction/