2015-08-19 66 views
0

對於我的主要故事板上的靜態標籤之一,它會打印出「可選(」美國「),但我希望它打印出」美國「。 ?問題是,我該如何擺脫「可選」的部分我已經嘗試過這樣做的:?可選()在我的文本視圖中

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)" 
       } 
      } 
     }) 




    } 

} 
+1

p.country是可選的,你需要解開它。 –

回答

1

if let p = placemarks!.first{ 
    self.addressLabel.text = "\(p.country)" 
} 

p.countryOptional<String>。你需要解開這個以便輸出它的內容(如果存在的話)。

if let country = placemarks?.first?.country { 
    self.addressLabel.text = country 
} 
+0

太棒了。非常感謝你的回覆。您能否解釋一下這個聲明中發生了什麼:'placemarks?。first?.country'?地標實際上代表什麼?首先?和國家?我爲這樣的noob問題感到抱歉...爲什麼我們需要這些選項?我對可選屬性有一個基本的瞭解,也就是說,它們是隻能保存兩種類型值的變量。指定類型的值和nil。預先感謝您...... – aejhyun

+0

在這種情況下,這些時期意味着什麼?我認爲這意味着調用某種方法是正確的?這在這方面意味着什麼?我對這種混亂的質疑表示歉意。 – aejhyun

+0

如果您選擇了一個變量,Xcode會顯示其定義和文檔(如果存在)。我的猜測是'placemarks'是一個對象數組,'.first'返回數組中的第一個對象。 –

相關問題