user12308611
user12308611

Reputation:

Initialize Array in Class - Swift

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.

Upvotes: 0

Views: 576

Answers (2)

Wimukthi Rajapaksha
Wimukthi Rajapaksha

Reputation: 1019

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

Upvotes: 0

vadian
vadian

Reputation: 285250

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)"
}

Upvotes: 2

Related Questions