How to access data in Class globally in any ViewController in the project
If your objective is to access the data globally for temporary storage, just create a struct for your transaction:
struct Transaction {
let date: Date
let quantity: Int
let price: Double
let code: String
}
Then just need to create a singleton and a property to store your transactions:
class Shared {
private init() { }
static var instance = Shared()
var transactions: [Transaction] = []
}
usage:
Shared.instance.transactions.append(Transaction(date: Date(), quantity: 2, price: 0.99, code: "item01"))
Shared.instance.transactions.append(Transaction(date: Date(), quantity: 3, price: 2.99, code: "item02"))
Shared.instance.transactions // [{date "Jan 10, 2017, 2:00 AM", quantity 2, price 0.99, code "item01"},
// {date "Jan 10, 2017, 2:00 AM", quantity 3, price 2.99, code "item02"}]
looping through your transactions and editing it:
for (index, transaction) in Shared.instance.transactions.enumerated() {
print(transaction)
if transaction.code == "item02" {
Shared.instance.transactions[index] = Transaction(date: transaction.date, quantity: transaction.quantity, price: transaction.price, code: "NEW CODE")
}
}
Shared.instance.transactions // [{date "Jan 10, 2017, 2:42 AM", quantity 2, price 0.99, code "item01"}, {date "Jan 10, 2017, 2:42 AM", quantity 3, price 2.99, code "NEW CODE"}]
If you want to have just a single transaction just add an optional variable to your Shared struct instead of the transactions array:
class Shared {
private init() { }
static var instance = Shared()
var transaction: Transaction?
}
and usage:
Shared.instance.transaction = Transaction(date: Date(), quantity: 5, price: 5.0, code: "P200")
print(Shared.instance.transaction?.code ?? "") // "P200\n"
if let transaction = Shared.instance.transaction {
Shared.instance.transaction = Transaction(date: transaction.date, quantity: transaction.quantity, price: transaction.price, code: "P300")
print(Shared.instance.transaction!) // "Transaction(date: 2017-01-10 05:13:58 +0000, quantity: 5, price: 5.0, code: "P300")\n"
}