Skip to content

Instantly share code, notes, and snippets.

@SpacyRicochet
Created March 22, 2016 22:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SpacyRicochet/25a6dadda4b0af13d221 to your computer and use it in GitHub Desktop.
Save SpacyRicochet/25a6dadda4b0af13d221 to your computer and use it in GitHub Desktop.
A playground messing around with Swift unit types and operators
//: Playground - noun: a place where people can play
import UIKit
protocol Money: CustomStringConvertible {
var amount: Double { get }
var inGold: Double { get }
var symbol: String { get }
}
extension Money {
var description: String {
return "\(amount)\(symbol)"
}
}
struct Copper: Money {
let amount: Double
var inGold: Double {
return amount * 0.01
}
var symbol: String {
return "cp"
}
}
struct Silver: Money {
let amount: Double
var inGold: Double {
return amount * 0.1
}
var symbol: String {
return "sp"
}
}
struct Gold: Money {
let amount: Double
var inGold: Double {
return amount
}
var symbol: String {
return "gp"
}
}
struct Platinum: Money {
let amount: Double
var inGold: Double {
return amount * 10
}
var symbol: String {
return "pp"
}
}
func + (lhs: Money, rhs: Money) -> Money {
return Gold(amount: lhs.inGold + rhs.inGold)
}
func - (lhs: Money, rhs: Money) -> Money {
return Gold(amount: lhs.inGold - rhs.inGold)
}
extension Int {
var copper: Money {
return Copper(amount: Double(self))
}
var silver: Money {
return Silver(amount: Double(self))
}
var gold: Money {
return Gold(amount: Double(self))
}
var platinum: Money {
return Platinum(amount: Double(self))
}
}
25.gold + 60.silver + 18.copper
struct Pouch: CustomStringConvertible {
let monies: [Money]
init(monies: [Money] = []) {
self.monies = monies
}
}
extension Pouch {
var description: String {
return monies.reduce("Pouch containing:\n", combine: { (current, money) -> String in
var result = current
if result.characters.count > 0 {
result += "\n"
}
result += " \(money)"
return result
})
}
}
infix operator <<< { associativity left precedence 160 }
func <<< (lhs: Pouch, rhs: Money) -> Pouch {
return Pouch(monies: lhs.monies + [rhs])
}
(Pouch() <<< 5.gold <<< 8.platinum <<< 900.silver).description
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment