Created
November 1, 2015 02:33
-
-
Save takaheraw/44dff56470f2c9c19ef5 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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