I deal with various units, i.e. distance , altitude , speed , volume , etc.
My goal is to have an elegant, unique way of formatting in an application, for example, calling myValue.formatted :
let mySpeed: Speed = 180 println(mySpeed.formatted) // 5.0 km/h let myAltitude: Altitude = 4000 println(myAltitude.formatted) // 4000 m
I thought this was a good example of using type aliases.
typealias Distance = Float typealias Altitude = Float typealias Speed = Float
For the formatted property formatted I tried with an extension type Float :
extension Float { var formatted: String { get { switch self { case is Altitude: return "\(self) m" case is Speed: return "\(self * 3.6) km/h" default: return "\(self)" } } } }
But the compiler says that my case blocks are always true .
Then I tried to extend one type:
extension Speed { var formatted: String { return "\(self * 3.6) km/h" } } extension Altitude { var formatted: String { return "\(self) m" } }
the compiler now clearly indicates the invalid "formatted" fix
OK, now itβs clear how type aliases work. But how do I get the .formatted property for different types of Floats in swift?
source share