Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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