Here’s Jamone Kelly‘s starting point. If you want to hop into the revisions, there’s a slightly earlier starting point but this is his properly working version.
After playing “Make it Swifter”, here’s my version.
I struggled a bit with the operator before settling on using the ° symbol. In my mind, I’m thinking the operator says “treat this value as degrees” and transparently perform any conversion to radians. I didn’t want to put a radian or angle symbol after it, which really doesn’t read as well to mean “radian-ify this”.
I’m not married to this approach. In hindsight, I might have created a new type Angle
with separate initializers (init(degrees: Double)
, init(radians:Double)
) and degreeRepresentation
and floatRepresentation
members. It just seems like a lot of excess work for relatively little reward here. (Although as a re-usable library component, it would probably be nice.)
Settling on the enumeration was hard too because I was leaning towards Units
with cases of Imperial
and Metric
, but then associating these specific raw values didn’t make sense. I ended up with wordier versions that supported the raw values being stored.
I am still using uppercase enumeration cases despite pressure to convert them to lower case members.
Paired assignments emphasize the parallel math, which feels both Swift-y and transgressive. I like them when they reflect corresponding operations, although your mileage may vary.
If I were pushing on this, I’d of course comment a lot more and probably add in some kind of protocol to support interop (representation and initialization) with CoreLocation.
How would you re-design this code? Drop a gist and share.
4 Comments
I experimented with angle types and came to pretty much the same conclusion – that the ° operator should just assume the value is degrees and convert it to radians. The ° is just an alias for a .degrees property, so you can type “90.degrees” if you want to (you can also do “1.radians” to get degrees).
See: https://github.com/dclelland/Degrad
Also see: https://github.com/dclelland/HOWL/blob/master/HOWL/Views/DialControl.swift – there’s a few in-use examples floating around in there
What advantages does this have over CLLocation’s “distanceFromLocation:” method?
This was an exercise in learning Swift and making code more Swifty. The whole distance/location stuff was incidental. 🙂
Took your Coordinate type and turned it into a protocol 🙂 had to split up the distanceFrom: method into milesFrom: and kilometersFrom:, as default arguments don’t work on protocol extensions 🙁
https://gist.github.com/worthbak/64fbfc15f0cde6350524