Biscuit128
Biscuit128

Reputation: 5408

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

Upvotes: 13

Views: 20945

Answers (6)

Abdul Samad Butt
Abdul Samad Butt

Reputation: 37

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())
    

Upvotes: 0

Supratik Majumdar
Supratik Majumdar

Reputation: 2466

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

Upvotes: 3

Josh Goldberg
Josh Goldberg

Reputation: 121

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

Upvotes: 8

Nikos M.
Nikos M.

Reputation: 13783

You can turn it to a String using this code:

var oneString = String(userLocation.coordinate.latitude)

Upvotes: -1

zisoft
zisoft

Reputation: 23078

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

Set the format paramater to your needs.

Upvotes: 10

hedzs
hedzs

Reputation: 447

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

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

Upvotes: 32

Related Questions