Skip to content

Instantly share code, notes, and snippets.

@takaheraw
Created November 1, 2015 02:33
Show Gist options
  • Save takaheraw/44dff56470f2c9c19ef5 to your computer and use it in GitHub Desktop.
Save takaheraw/44dff56470f2c9c19ef5 to your computer and use it in GitHub Desktop.
class Purchase : CustomStringConvertible {
private let product:String
private let price:Float
init(product:String, price:Float) {
self.product = product
self.price = price
}
var description:String {
return product
}
var totalPrice:Float {
return price
}
}
class CustomAccount {
let customName:String
var purchases = [Purchase]()
init(name:String) {
self.customName = name
}
func addPurchase(purchase:Purchase) {
self.purchases.append(purchase)
}
func printAccount() {
var total:Float = 0
for p in purchases {
total += p.totalPrice
print("Purchase \(p), Price " +
"\(formatCurrencyString(p.totalPrice))")
}
print("Total due: \(formatCurrencyString(total))")
}
func formatCurrencyString(number:Float) -> String {
let formatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
formatter.locale = NSLocale(localeIdentifier: "en_US")
return formatter.stringFromNumber(number) ?? ""
}
}
let account = CustomAccount(name: "Joe")
account.addPurchase(Purchase(product: "Red Hat", price: 10))
account.addPurchase(Purchase(product: "Scarf", price: 20))
account.printAccount()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment