對於我的主要故事板上的靜態標籤之一,它會打印出「可選(」美國「),但我希望它打印出」美國「。 ?問題是,我該如何擺脫「可選」的部分我已經嘗試過這樣做的:?可選()在我的文本視圖中
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)"
}
}
})
}
}
p.country是可選的,你需要解開它。 –