[英]How to make value in func to global constant in Swift
如何將經度和緯度值(在應用運行時均顯示一個緯度)設置為全局常量? 這些值是當前
String(format: "4.4f", latestLocation.coordinate.latitude)
和
String(format: "4.4f", latestLocation.coordinate.longitude)
我想讓這些成為全局常量,例如可以在函數外部訪問的userlatitude
和userlongitude
。 我是否必須退還有意義的希望。
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)
}
這樣,您可以將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")
之后,您可以在任何需要的地方以這種方式訪問它:
//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
在import語句下面定義您的Variable。 就像是,
import UIKit let latitude = 4.0 // Do Stuff - This Variable access in Any class. Thanx Swift....
另一種解決方案是將您的值放在.plist/NSUser
Default中,並使用適當的密鑰在每個類(您希望在何處使用)中進行訪問。
一種解決方案是將值存儲為NSUserDefaults,這使您可以在需要時訪問值。 嘗試此鏈接以獲取更多信息http://www.codingexplorer.com/nsuserdefaults-a-swift-introduction/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.