gpt4 book ai didi

swift - 什么都不打印而不是 nil

转载 作者:行者123 更新时间:2023-11-28 05:27:58 26 4
gpt4 key购买 nike

我创建了一个 View ,该 View 在 map 上显示用户位置,并在 View 中的两个标签中显示用户位置。它并不总是有 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)"

}

}
})
}

最佳答案

self.adress.text = "\(p.thoroughfare) \(p.subThoroughfare)" 

使用 p.subThoroughfare 而不是 subThoroughfare。此外,您可以为此使用 nil 合并运算符 (??)

var subThoroughfare = p.subThoroughfare ?? "" 

如果 p.subThoroughfare 不为 nil,将计算为 p.subThoroughfare,否则将计算为 ""

所以:

var subThoroughfare = p.subThoroughfare ?? "" 
self.adress.text = "\(p.thoroughfare) \(subThoroughfare)"
self.adress2.text = " \(p.postalCode) \(p.subLocality)"

关于swift - 什么都不打印而不是 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30215440/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com