Thursday 15 September 2011

ios - Extending type aliases in swift -



ios - Extending type aliases in swift -

i dealing different units, i.e. distance, altitude, speed, volume, etc.

my goal have elegant, unique way format them in app, illustration calling myvalue.formatted:

let myspeed: speed = 180 println(myspeed.formatted) // 5.0 km/h allow myaltitude: height = 4000 println(myaltitude.formatted) // 4000 m

i thought case using type aliases.

typealias distance = float typealias height = float typealias speed = float

for formatted property, tried extension of type float:

extension float { var formatted: string { { switch self { case altitude: homecoming "\(self) m" case speed: homecoming "\(self * 3.6) km/h" default: homecoming "\(self)" } } } }

but compiler says case blocks true.

then tried extend single type:

extension speed { var formatted: string { homecoming "\(self * 3.6) km/h" } } extension height { var formatted: string { homecoming "\(self) m" } }

the compiler states invalid redeclaration of 'formatted'

ok, it's clear how type aliases work. how .formatted property different types of floats in swift?

typealias alter or rename type.it not create user type you.you extending float speed,altitude again.

you can pass 180 custom struct conforming literals types.

let myspeed: speed = 180

floatliteralconvertible , integerliteralconvertible give same functionality want , can straight assign values custom struct types assign float

struct speed: floatliteralconvertible,integerliteralconvertible { var distance:float init(floatliteral value: float) { distance = value } init(integerliteral value: int){ distance = float(value) } var formatted: string { homecoming "\(distance * 3.6) km/h" } } allow myspeed: speed = 180.0 println(myspeed.formatted) // 5.0 km/h

ios swift

No comments:

Post a Comment