0

EDIT: Full code now posted since it was requested.

Why am I getting the word "optional" before my placemarks on the app labels?

I originally unwrapped each property like this \(p.thoroughfare!), and it worked, but only when there was a subThoroughfare. I couldn't unwrap \(subThoroughfare) because I don't know where to do it, therefore the app crashed when there wasn't a 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)"

            }


        }

    })

2 Answers 2

2

You are getting the Optional("string") because you are not unwrapping these optional vars.

if var str:String? is nil and you set myLabel.text = str, your label text will be empty! If it has a value let's say str = "yaw!" and you set myLabel.text = str, the label will show yaw!

Now if your string is nil and you use string interpolation myLabel.text = \(str), your label text will show nil. If you set str = "yaw!" and myLabel.text = \(str), the label will show Optional("yaw!")

To solve your problem you have to unwrap your vars in a safe way:

Create a var to hold the full string and then add the non nil values to this string.

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

Replicate the 2nd line to every attribute p.thoroughfare, p.subLocality etc.

And finally, set self.addressLabel.text = fullString

0

You are getting Optional("something") because:

  1. Your variable is defined as an optional (meaning it could be nil).
  2. You are using Swift.print() to display the string.

If it is not nil and you are not using Swift.print() to display the string, you will not get the word "Optional" and the string value in quotes, in parentheses.

You should check placemarks.count before attempting to accessing a value in the array, even if you use an array index of zero (as in your example code). This should be part of your error checking.

As for the rest, I am not sure what you are trying to do. If you can be more specific I might be able to give some suggestions.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.