Skip to content

Instantly share code, notes, and snippets.

@AdrianBinDC
Last active December 15, 2023 02:12
Show Gist options
  • Save AdrianBinDC/081e4af871d7c60018c9bd9b521f5ca3 to your computer and use it in GitHub Desktop.
Save AdrianBinDC/081e4af871d7c60018c9bd9b521f5ca3 to your computer and use it in GitHub Desktop.
Convert Distances in Swift using Measurement

Distance conversion in Swift

As of iOS 10, the Measurement class was introduced, which obviates the need lookup values and create constants to convert values. Here is a simple extension to convert distances.

extension Double {
  func convert(from originalUnit: UnitLength, to convertedUnit: UnitLength) -> Double {
    return Measurement(value: self, unit: originalUnit).converted(to: convertedUnit).value
  }
}

Usage

let miles = 1.0
let metersInAMile = miles.convert(from: .miles, to: .meters)

let mileInFeet = 5280.0
let feetInAMile = mileInFeet.convert(from: .feet, to: .miles)

let marathonInFeet = 138_435.0
let milesInMarathon = marathonInFeet.convert(from: .feet, to: .miles)
let kmInMarathon = marathonInFeet.convert(from: .feet, to: .kilometers)

let inch = 1.0
let centimetersInInch = inch.convert(from: .inches, to: .centimeters)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment