Skip to content

Instantly share code, notes, and snippets.

@bizz84
Last active August 29, 2015 14:17
Show Gist options
  • Save bizz84/ca61b29eb9719b4b7f4e to your computer and use it in GitHub Desktop.
Save bizz84/ca61b29eb9719b4b7f4e to your computer and use it in GitHub Desktop.
SwiftStrongTyping-DistanceTimeVelocity
// 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?
@bizz84
Copy link
Author

bizz84 commented Mar 29, 2015

Is there a way to do strong type checking like this without boxing the values inside structs?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment