gpt4 book ai didi

swift - 为什么我在应用程序标签上的地标前收到 "optional"字样?

转载 作者:行者123 更新时间:2023-11-28 13:01:18 25 4
gpt4 key购买 nike

编辑:自请求以来,现在已发布完整代码。

为什么我在应用标签上的地标前会看到“可选”一词?

我最初像这样\(p.thoroughfare!) 展开了每个属性,并且它起作用了,但只有当有 subThoroughfare 时。我无法解包 \(subThoroughfare) 因为我不知道在哪里做,因此当 没有 subThoroughfare 时应用程序崩溃了。

enter image description here

    import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

var manager:CLLocationManager!


@IBOutlet var latitudeLabel: UILabel!
@IBOutlet var longitudeLabel: UILabel!
@IBOutlet var courseLabel: UILabel!
@IBOutlet var speedLabel: UILabel!
@IBOutlet var altitudeLabel: UILabel!
@IBOutlet var addressLabel: UILabel!

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

manager = CLLocationManager()
manager.delegate = self
manager.desiredAccuracy - kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()


}

//NOTE: [AnyObject] changed to [CLLocation]

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

print(locations)

//userLocation - there is no need for casting, because we are now using CLLocation object

var userLocation:CLLocation = locations[0]

self.latitudeLabel.text = "\(userLocation.coordinate.latitude)"

self.longitudeLabel.text = "\(userLocation.coordinate.longitude)"

self.courseLabel.text = "\(userLocation.course)"

self.speedLabel.text = "\(userLocation.speed)"

self.altitudeLabel.text = "\(userLocation.altitude)"

CLGeocoder().reverseGeocodeLocation(userLocation, completionHandler: { (placemarks, error) -> Void in

if (error != nil) {

print(error)

} else {

if let p = placemarks?[0] {

var subThoroughfare : String = ""

if (p.subThoroughfare != nil) {

subThoroughfare = p.subThoroughfare!

}

self.addressLabel.text = "\(subThoroughfare) \(p.thoroughfare) \n \(p.subLocality) \n \(p.subAdministrativeArea) \n \(p.postalCode) \n \(p.country)"

}


}

})

最佳答案

你得到了 Optional("string") 因为你没有解包这些可选变量。

如果 var str:String?nil 并且您设置了 myLabel.text = str,您的标签文本将为空!如果它有一个值,比如说 str = "yaw!" 并且您设置了 myLabel.text = str,标签将显示 yaw!/p>

现在,如果您的字符串是 nil 并且您使用字符串插值 myLabel.text =\(str),您的标签文本将显示 nil .如果您设置 str = "yaw!"myLabel.text =\(str),标签将显示 Optional("yaw!")

要解决您的问题,您必须以安全的方式解包您的变量:

创建一个 var 来保存完整的字符串,然后将非 nil 值添加到该字符串。

    var fullString:String = ""
if let _ = p.subThoroughfare { fullString += "\(p.subThoroughfare!)" } // Check if the attribute is not nil before adding it to the string

将第 2 行复制到每个属性 p.thoroughfarep.subLocality

最后,设置 self.addressLabel.text = fullString

关于swift - 为什么我在应用程序标签上的地标前收到 "optional"字样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33747829/

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