Reputation: 826
Need help converting some code to Swift 4. Starting getting errors and not sure how to convert this piece of code. I am having trouble with String
and doubleValue
.
let distanceInMeters: Double = userLocation.distance(from: businessLocation)
let distanceInMiles: Double = ((distanceInMeters.description as? String).doubleValue * 0.00062137)
let distanceLabelText = "\(distanceInMiles.string(2)) miles away"
Upvotes: 0
Views: 542
Reputation: 58049
You are converting a String
back and forth unnecessarily. Moreover, you should use String
formatters to print doubles with a given precision.
Here is your code in a cleaner format:
let distanceInMeters = userLocation.distance(from: businessLocation)
let distanceInMiles = distanceInMeters * 0.00062137
let distanceLabelText = String(format: "%.2f miles away", distanceInMiles)
Upvotes: 5
Reputation: 6982
distanceInMeters
is a Double
, which you try to convert to String
, which you then try to convert back to Double
. Why? Just do
let distanceInMiles: Double = distanceInMeters * 0.00062137
As for
distanceInMiles.string(2)
Double no longer has a string
method - just use String
s initializer
let distanceLabelText = "\(String(distanceInMiles)) miles away"
Upvotes: 1