对于我主要故事板上的一个静态标签,它会打印出#34; Optional(" United States")。但是,我希望打印出#34;美国"。所以我的问题是,如何摆脱" Optional"部分?我已经尝试过了:
if let p = placemarks!.first{
self.addressLabel.text = "\(p.country)"
}
我认为感叹号应该打开"展开"有些价值吗?但是,即使我p = placemarks!.first
,也会打印出"可选("美国")。
以下是我的其余代码,以防你需要一些上下文:
//
// ViewController.swift
// Map Demo Rob 2
//
// Created by Jae Hyun Kim on 8/17/15.
// Copyright © 2015 Jae Hyun Kim. All rights reserved.
//
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var latitudeLabel: UILabel!
@IBOutlet weak var longitudeLabel: UILabel!
@IBOutlet weak var courseLabel: UILabel!
@IBOutlet weak var speedLabel: UILabel!
@IBOutlet weak var altitudeLabel: UILabel!
@IBOutlet weak var addressLabel: UILabel!
var manager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
manager = CLLocationManager()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print(locations)
let 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
print(userLocation)
if error != nil {
print(error)
return
}
else {
if let p = placemarks?.first{
self.addressLabel.text = "\(p.country)"
}
}
})
}
}
答案 0 :(得分:1)
在
if let p = placemarks!.first{
self.addressLabel.text = "\(p.country)"
}
p.country
是Optional<String>
。您需要打开它以便仅输出它的内容(如果存在)。
if let country = placemarks?.first?.country {
self.addressLabel.text = country
}