我创建了一个视图,在地图上显示用户位置,并在视图中的两个标签中显示用户位置。它并不总是有一个subThoroughfare,所以" nil"印在标签上。我可以做什么只是打印而不是" nil"在标签? 谢谢你的帮助
import UIKit
import CoreLocation
import MapKit
class Kart: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
@IBOutlet var myMap: MKMapView!
var locationManager = CLLocationManager()
@IBOutlet var adress: UILabel!
@IBOutlet var adress2: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
println("Feil")
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
var userLocation:CLLocation = locations[0] as! CLLocation
locationManager.stopUpdatingLocation()
let location = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude)
let span = MKCoordinateSpanMake(0.01, 0.01)
let region = MKCoordinateRegion(center: location, span: span)
myMap.setRegion(region, animated: true)
CLGeocoder().reverseGeocodeLocation(userLocation, completionHandler: { (placemarks, error) -> Void in
if (error != nil) {
println(error)
} else {
if let p = CLPlacemark(placemark: placemarks?[0] as! CLPlacemark) {
var subThoroughfare:String = ""
if (p.subThoroughfare != nil) {
subThoroughfare = p.subThoroughfare
}
self.adress.text = "\(p.thoroughfare) \(p.subThoroughfare)"
self.adress2.text = " \(p.postalCode) \(p.subLocality)"
}
}
})
}
答案 0 :(得分:2)
--cpu-set
使用p.subThoroughfare而不是subThoroughfare。此外,您可以使用nil合并运算符(??)
self.adress.text = "\(p.thoroughfare) \(p.subThoroughfare)"
如果它不是零,将评估为p.subThoroughfare,否则它将评估为“”
这样:
var subThoroughfare = p.subThoroughfare ?? ""
答案 1 :(得分:0)
将打印subThoroughfare的行移动到if语句中:
if (p.subThoroughfare != nil) {
subThoroughfare = p.subThoroughfare
self.adress.text = "\(p.thoroughfare) \(p.subThoroughfare)"
}
else
self.adress.text = "\(p.thoroughfare)"
另外:看起来你并没有使用那个subThoroughfare变量。