|
// |
|
// main.swift |
|
// WithdrawTool |
|
// |
|
// The MIT License (MIT) |
|
// |
|
// Copyright (c) 2015 Marius Rackwitz |
|
// |
|
// Permission is hereby granted, free of charge, to any person obtaining a copy of |
|
// this software and associated documentation files (the "Software"), to deal in |
|
// the Software without restriction, including without limitation the rights to |
|
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of |
|
// the Software, and to permit persons to whom the Software is furnished to do so, |
|
// subject to the following conditions: |
|
// |
|
// The above copyright notice and this permission notice shall be included in all |
|
// copies or substantial portions of the Software. |
|
// |
|
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
|
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS |
|
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR |
|
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER |
|
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN |
|
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
|
// |
|
|
|
import Foundation |
|
|
|
public struct Account { |
|
public enum Error : ErrorType { |
|
case TransactionExceedsFunds |
|
case NonPositiveTransactionNotAllowed(amount: Int) |
|
} |
|
|
|
var fund: Int |
|
|
|
public mutating func withdraw(amount: Int) throws { |
|
guard amount < fund else { |
|
throw Error.TransactionExceedsFunds |
|
} |
|
guard amount > 0 else { |
|
throw Error.NonPositiveTransactionNotAllowed(amount: amount) |
|
} |
|
fund -= amount |
|
} |
|
} |
|
|
|
enum Error : ErrorType { |
|
case NoArgumentGiven |
|
case ArgumentIsNotAnInteger |
|
} |
|
|
|
var arguments = Process.arguments |
|
|
|
// Remove the executable name. |
|
assert(arguments.count >= 1) |
|
arguments.removeAtIndex(0) |
|
|
|
guard let firstArg = arguments.first else { |
|
throw Error.NoArgumentGiven |
|
} |
|
guard let amount = Int(firstArg) else { |
|
throw Error.ArgumentIsNotAnInteger |
|
} |
|
|
|
let dict = NSMutableDictionary(contentsOfFile: "account.plist") ?? NSMutableDictionary() |
|
let fund = dict["fund"] as? Int ?? 100 |
|
|
|
var account = Account(fund: fund) |
|
|
|
do { |
|
try account.withdraw(amount) |
|
dict["fund"] = account.fund |
|
dict.writeToFile("account.plist", atomically: true) |
|
} catch Account.Error.NonPositiveTransactionNotAllowed(let amount) { |
|
print("Amount (\(amount)) must be positive.") |
|
} catch Account.Error.TransactionExceedsFunds { |
|
print("Amount (\(amount)) exceeds account balance (\(account.fund)).") |
|
} catch { |
|
print("An unexpected error <\(error)> occured.") |
|
} |