Skip to content

Instantly share code, notes, and snippets.

@lahariganti
Last active November 13, 2022 10:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lahariganti/14f310916cf267353d52ea3c1ab0406e to your computer and use it in GitHub Desktop.
Save lahariganti/14f310916cf267353d52ea3c1ab0406e to your computer and use it in GitHub Desktop.
import Foundation
import UIKit
extension Double {
func formatElevation() -> (AttributedString, AttributedString) {
let measurement = Measurement(value: self, unit: Locale.current.usesMetricSystem ? UnitLength.meters : UnitLength.feet)
var resultString = measurement.formatted(.measurement(width: .narrow, usage: .road, numberFormatStyle: .number).attributed)
let unitContainer = AttributeContainer.measurement(.unit)
let colorContainer = AttributeContainer.foregroundColor(.white)
resultString.replaceAttributes(unitContainer, with: colorContainer)
var resultStringCopy = resultString
// The closure will be called multiple times, and $0.value will be nil or not depending on if it's in the color range or not
resultString.transformingAttributes(AttributeScopes.UIKitAttributes.ForegroundColorAttribute.self) {
if $0.value == nil {
resultString.removeSubrange($0.range)
} else {
resultStringCopy.removeSubrange($0.range)
}
}
return (resultStringCopy, resultString)
}
}
print (35.0.formatElevation())
//(40 {
// Foundation.MeasurementAttribute = value
// Foundation.NumberFormatPart = integer
//}, m {
// NSColor = UIExtendedGrayColorSpace 1 1
//})
//
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment