Last active
August 29, 2015 14:17
-
-
Save bizz84/ca61b29eb9719b4b7f4e to your computer and use it in GitHub Desktop.
SwiftStrongTyping-DistanceTimeVelocity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Playground - noun: a place where people can play | |
struct Distance { | |
let value: Double | |
} | |
struct Time { | |
let value: Double | |
} | |
struct Velocity { | |
let value: Double | |
init(distance: Distance, time: Time) { | |
value = distance.value / time.value | |
} | |
} | |
// Verbose | |
let d1 = Distance(value: 100.0) | |
let t1 = Time(value: 10.0) | |
let v1 = Velocity(distance: d1, time: t1) | |
// 'Velocity' is not convertible to 'Distance' | |
let vv1 = Velocity(distance: v1, time: t1) | |
extension Double { | |
func asDistance() -> Distance { | |
return Distance(value: self) | |
} | |
func asTime() -> Time { | |
return Time(value: self) | |
} | |
} | |
func /(left: Distance, right: Time) -> Velocity { | |
return Velocity(distance: left, time: right) | |
} | |
// Less verbose | |
let d2 = 100.0.asDistance() | |
let t2 = 10.0.asTime() | |
let v2 = d2 / t2 | |
// Cannot invoke '/' with an argument list of type '(Velocity, Time)' | |
let vv2 = v2 / t2 | |
// Any better way? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is there a way to do strong type checking like this without boxing the values inside structs?