Swift 2 - 自动定位时出现可选字符串

Swift 2 - Optional Strings Appear upon Automatic Location

我的应用程序中有一个自动定位功能,但自从我更新到 swift 2 后,我开始在显示每个部分的位置详细信息之前出现 "Optional String",关于如何使用的任何建议解决这个问题?

这是它显示的内容:

Optional("Cupertino")
Optional("95014")
Optional("CA")
Optional("United States")
--------------------
*** location: ***
Optional(<+37.33233141,-122.03121860> +/- 5.00m (speed 0.00 mps / course -1.00) @ 10/11/15, 11:05:28 PM British Summer Time)

下面是我的代码

import UIKit
import Foundation
import MapKit
import CoreLocation
import SystemConfiguration
import MobileCoreServices

class GeoLocation: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

    // GeoLocation IBOutlets Set

    @IBOutlet weak var mapView: MKMapView!
    @IBOutlet weak var myAddressView: UITextField!
    @IBOutlet weak var myLocationVIew: UITextField!

    @IBOutlet weak var BUTTONA: UIButton!

    @IBAction func BrightnessIncrease(sender: AnyObject) {

        UIScreen.mainScreen().brightness = CGFloat(1.0)
    }

    @IBAction func BrightnessDecrease(sender: AnyObject) {

        UIScreen.mainScreen().brightness = CGFloat(0.4)
    }

    var locationManager:CLLocationManager!

    override func viewDidLoad() {
        super.viewDidLoad()

        myAddressView.hidden = true
       myLocationVIew.hidden = true

        locationManager = CLLocationManager()
        locationManager.requestAlwaysAuthorization()
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.delegate = self
        locationManager.startUpdatingLocation()

        mapView.showsUserLocation = true
        mapView.delegate = self
        mapView.mapType = MKMapType.Hybrid
        CLLocationManager().requestAlwaysAuthorization()

        self.myAddressView.borderStyle = UITextBorderStyle.RoundedRect

        self.myLocationVIew.borderStyle = UITextBorderStyle.RoundedRect

        // Do any additional setup after loading the view, typically from a nib.
    }

    @IBAction func DATA2(sender: AnyObject) {

        if myAddressView.text != ""
        {
            SECTIONB = myAddressView.text
        }
        else
        {
            performSegueWithIdentifier("Transferfile", sender: sender)

            }
    }

    @IBAction func DATA3(sender: AnyObject) {

        if myLocationVIew.text != ""
        {
            SECTIONC = myLocationVIew.text
        }
        else
        {
            performSegueWithIdentifier("Transferfile", sender: sender)

        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    // Map Display and Region Zoom

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let regionToZoom = MKCoordinateRegionMake(manager.location!.coordinate, MKCoordinateSpanMake(0.005, 0.005))

        mapView.setRegion(regionToZoom, animated: true)

        myLocationVIew.text = "\(locationManager.location)"

        CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: { (placemarks, error) -> Void in
            if error != nil {
                print("Error: " + error!.localizedDescription)
                return
            }
            if placemarks!.count > 0 {
            let pm = placemarks?[0] 
            self.displayLocationInfo(pm!)

            }
        })
    }

    func displayLocationInfo(placemark: CLPlacemark) {

        // This Section stops updating location constantly.

        //   self.locationManager.stopUpdatingLocation()

        // This Section display address parameters in a column on UILabel
        //            var address = (
        //                (placemark.subThoroughfare),
        //                (placemark.thoroughfare),
        //                (placemark.subLocality),
        //                (placemark.locality),
        //                (placemark.postalCode),
        //                (placemark.administrativeArea),
        //                (placemark.country))

        //          myAddressView.text = "\(address)"


        myAddressView.text = " \(placemark.subThoroughfare) \(placemark.thoroughfare) \r \(placemark.subLocality) \r \(placemark.locality) \(placemark.administrativeArea) \(placemark.postalCode) \r \(placemark.country)"

        print("-----START UPDATE-----")
        print(placemark.subThoroughfare)
        print(placemark.thoroughfare)
        print(placemark.locality)
        print(placemark.postalCode)
        print(placemark.administrativeArea)
        print(placemark.country)
        print("--------------------")
        print("*** location: ***")
        print(locationManager.location)
        print("--------------------")
        print("*** addressDictionary: ***")
        print(placemark.addressDictionary)
        print("-----END OF UPDATE-----")

    }

    func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
        print("Error: " + error.localizedDescription)

    }
}

guard letif let 展开字符串。如果您选择单击 placemark 属性,例如 subThoroughfare,它会说这是一个可选字符串。

你也可以像解释的那样展开here

let subThoroughfare = placemark.subThoroughfare ?? ""

let subThoroughfare = placemark.subThoroughfare ?? "Default subThoroughfare"

完整示例:

    let subThoroughfare = placemark.subThoroughfare ?? ""
    let thoroughfare = placemark.thoroughfare ?? ""
    let subLocality = placemark.subLocality ?? ""
    let locality = placemark.locality ?? ""
    let administrativeArea = placemark.administrativeArea ?? ""
    let postalCode = placemark.postalCode ?? ""
    let country = placemark.country ?? ""

    myAddressView.text = " \(subThoroughfare) \(thoroughfare) \r \(subLocality) \r \(locality) \(administrativeArea) \(postalCode) \r \(country)"

当展开字符串时,使用 Nil Coalescing Operator 是有意义的。按照第一个 link 了解更多信息。它允许您轻松解包可选字符串或在它为 nil 时使用 empty/default 字符串。对于几乎所有其他选项,您将需要使用 if letguard let 语句。

永远不要强制解包可选(使用 ! 称为强制解包)值 return 从像 Core Location 这样的框架中编辑。您无法知道所有可能的 return 值以及它们何时会或不会为零。只有当你创建它们并且绝对确定它们不为零时才强制展开可选值。例如,在分配一个值之后,强制解包可能没问题。


关于选项:optionals

关于守卫:

它打印 Optional String 因为您尝试打印的变量是 Optional 变量,这意味着变量可能有也可能没有值。

如果您确定变量已经保存了值,只需在变量末尾放置一个 !unwrap 即可。

    print(placemark.subThoroughfare!)
    print(placemark.thoroughfare!)
    print(placemark.locality!)
    print(placemark.postalCode!)
    print(placemark.administrativeArea!)

如果您不确定,请尝试检查它是否等于 nil(通过使用 Nil Coalescing Operator),如果它是 nil:

,则打印默认值
    print(placemark.subThoroughfare ?? "")
    print(placemark.thoroughfare ?? "")
    print(placemark.locality ?? "")
    print(placemark.postalCode ?? "")
    print(placemark.administrativeArea ?? "")