'CLLocationDegrees to String variable in Swift

Given that the code

var latitude = userLocation.coordinate.latitude

returns a CLLocationDegrees Object, how can I store the value in to a variable so that I can apply it as the text of a label.

I can print the variable to the console without any issues but obviously that doesn't help me too much!

Looking through the valuable options through the autocomplete i see there is a description;

var latitude = userLocation.coordinate.latitude.description

But this is returning me null?

Thanks



Solution 1:[1]

You can turn it to a String using this code:

var oneString = String(userLocation.coordinate.latitude)

Solution 2:[2]

since CLLocationDegrees is just a typedef for Double, you can easily assign it to a string var, ie:

var latitudeText:String = "\(userLocation.coordinate.latitude)"

Solution 3:[3]

let latitudeText = String(format: "%f", userLocation.coordinate.latitude)

Set the format paramater to your needs.

Solution 4:[4]

nothing here worked for me. The closest I got was "Optional(37.8)" for a latitude value, I think because the CLLocationCoordinate2D is an optional class parameter. Here is what I ended up doing to get a plain string:

let numLat = NSNumber(double: (self.myLocation?.latitude)! as Double)
let stLat:String = numLat.stringValue

Solution 5:[5]

var lat = userLocation.coordinate.latitude
var latData = String(stringInterpolationSegment: lat)

Solution 6:[6]

The simplest and easiest way of doing this is the following way.

  1. Make an extension of CLLocationDegrees

    import Foundation
    import CoreLocation
    
    extension CLLocationDegrees {
    
     func toString() -> String {
          return "\(self)"
       }
    }
    
  2. Use it like this

    print(searchedPlace.coordinate.latitude.toString())
    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nikos M.
Solution 2 hedzs
Solution 3 zisoft
Solution 4 Josh Goldberg
Solution 5 Supratik Majumdar
Solution 6 Abdul Samad Butt