Search code examples
iosswiftcllocation

Convert CLLocationSpeed to long in Swift


I’m trying to get GPS speed in Swift. I've set everything up and am now trying to do some calculations. I want to convert the MS "string" to KMH. So I'm trying to convert the type to long, but I can’t get it to work.

I have tried this:

var ms: long?
ms = LocationManager.location.speed

But I got "CLLocationspeed is not convertible to long”

I’m new to iOS programming and Swift so I don't know how to fix this.


Solution

  • You should really start by reading the Swift Book, however:

    long isn’t a standard type in Swift (not sure where you’ve managed to find one :). An appropriate integer type to use would be Int (unless exact size matters to you – but it probably doesn’t). But CLLocationSpeed in CoreLocation is a typealias for Double and you should probably stick with that for speed calculations.

    In Swift, most conversions between types do not happen implicitly. If you really wanted a Double to become an Int, you need to explicitly convert it i.e. let ms = Int(LocationManager.location.speed).

    This feels like a pain when you are coming from C-like languages. But there are good reasons behind it. For example, what should happen to the fractional part of the floating-point number when you assign it to an integer type? Might you have forgotten your function is returning a floating point number and have accidentally introduced a truncation bug?

    To make up for this, Swift also has type inference. So unless you want to explicitly control the types, you don’t even have to give them:

    // type of ms is automatically inferred to be CLLocationSpeed (alias for Double)
    let ms = LocationManager.location.speed
    // 3.6 floating-point literal is automatically converted to appropriate type
    // type and kph is automatically a Double
    let kph = ms * 3.6
    

    Most of the time you don’t need to give a type, just leave it to be inferred it from the context.