Created
March 22, 2016 22:52
-
-
Save SpacyRicochet/25a6dadda4b0af13d221 to your computer and use it in GitHub Desktop.
A playground messing around with Swift unit types and operators
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 | |
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