Type alias extension in fast

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?

+6
source share
2 answers

typealias just change or rename the type. It does not create another type of user for you. You are actually expanding Float for Speed , Altitude .

You can pass 180 into your custom structure by combining Literals types.

 let mySpeed: Speed = 180 

FloatLiteralConvertible and IntegerLiteralConvertible will provide you with the same functionality you want and you can directly assign values ​​to your custom struct types when assigning Float

 struct Speed: FloatLiteralConvertible,IntegerLiteralConvertible { var distance:Float init(floatLiteral value: Float) { distance = value } init(integerLiteral value: Int){ distance = Float(value) } var formatted: String { return "\(distance * 3.6) km/h" } } let mySpeed: Speed = 180.0 println(mySpeed.formatted) // 5.0 km/h 
+5
source

Distance , Altitude and Speed always of the same type - Float and have the same formatted property. This is how the compiler sees your code:

 extension Float { var formatted: String { get { switch self { case is Float: return "\(self) m" case is Float: return "\(self * 3.6) km/h" default: return "\(self)" } } } } 

I think you need to create small wrappers for your functionality:

 struct Distance { var value: Float var formatted: String { return "\(value) m" } init(_ value: Float) { self.value = value } } let myDistance = Distance(123) myDistance.formatted 
+1
source

Source: https://habr.com/ru/post/977177/


All Articles