CLLocationDegrees to String variable in Swift
Asked Answered
B

6

13

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

Bearnard answered 1/10, 2014 at 13:22 Comment(1)
#29466905Agateware
P
-1

You can turn it to a String using this code:

var oneString = String(userLocation.coordinate.latitude)
Pesthole answered 1/10, 2014 at 14:32 Comment(1)
This works fine. Just make sure you are not passing an optional, which userLocation often is.Discontinuity
O
31

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

var latitudeText:String = "\(userLocation.coordinate.latitude)"
Oba answered 1/10, 2014 at 14:21 Comment(3)
note: the explicit type definiton is just optional, the assignment works without it ofcOba
This is the easiest solution on this page. Also works with : var lat = "\(result.location.coordinate.latitude)"Youngstown
Cannot convert value of type 'CLLocationDegrees?' to specified type 'String'Moss
Z
10
let latitudeText = String(format: "%f", userLocation.coordinate.latitude)

Set the format paramater to your needs.

Zwinglian answered 1/10, 2014 at 14:28 Comment(0)
H
8

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
Haletta answered 11/3, 2015 at 2:51 Comment(0)
A
3
var lat = userLocation.coordinate.latitude
var latData = String(stringInterpolationSegment: lat)
Abaft answered 4/9, 2015 at 18:13 Comment(1)
Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem.Morn
M
0

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())
    
Morville answered 23/4, 2022 at 7:13 Comment(0)
P
-1

You can turn it to a String using this code:

var oneString = String(userLocation.coordinate.latitude)
Pesthole answered 1/10, 2014 at 14:32 Comment(1)
This works fine. Just make sure you are not passing an optional, which userLocation often is.Discontinuity

© 2022 - 2024 — McMap. All rights reserved.