0

I am strugeling to work with the array accounts, I don't really know how I should handle it, how I should initialize it in order to correctly append the object accountFromJohn to the list accounts.

class Bank {
    var bicCode : String
    var address : String
    var customer : Customer
    var accounts : [BankAccount] = []
    init(bicCode : String, address : String, customer : Customer) {
        self.bicCode = bicCode
        self.address = address
        self.customer = customer
    }
}

var accountFromJohn = BankAccount(accountNumber : 192, balance : 20, customer : John)
var ING = Bank(bicCode : "LUING18", address : "Avenue du Swing", customer : Paul)

ING.accounts.append(accountFromJohn)

print(ING.accounts) // output : [main.BankAccount] ; wanted output : [accountFromJohn]

Best Reagars, Thanks in advance.

1
  • accountFromJohn is a variable name. Variable names exist purely for human interpretation, and don't exist at all at runtime. The BankAccount instance that's called accountFromJohn is actually some memory address, or some set of CPU registers. The program is telling you that ING.accounts contains one instance of type main.BankAccount. It doesn't know anything about whether you choose to call that instance accountFromJohn or magicUnicornRainbowPoops. Commented Apr 7, 2020 at 18:16

2 Answers 2

2

Everything is fine.

The array contains an instance of BankAccount rather than an arbitrary variable name accountFromJohn.

Prove it by printing

print(ING.accounts.first?.customer ?? "Accounts is empty")

However it's possible to print accountFromJohn. in BankAccount adopt CustomStringConvertible and add the property

var description : String {
    return "accountFrom\(customer)"
}
Sign up to request clarification or add additional context in comments.

Comments

0

For this as one approach you can assign values to accounts while initialisation of objects.

class Bank {
    var bicCode : String
    var address : String
    var customer : Customer
    var accounts : [BankAccount]
    init(bicCode : String, address : String, customer : Customer, accounts: [BankAccount]) {
        self.bicCode = bicCode
        self.address = address
        self.customer = customer
        self.accounts = accounts
    }
}

Then you can work with the objects properly.

var accountFromJohn = [BankAccount(accountNumber : 192, balance : 20, customer : John)]
var ING = Bank(bicCode : "LUING18", address : "Avenue du Swing", customer : Paul, accounts: accountFromJohn)

And then you can append data to Bank list like yourObject.append(ING), if you want to change values of accounts, you can do it by yourObject[desiredElement].accounts.append(accountsData) and if you need to retrieve values yourObject[desiredElement].accounts

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.