[英]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.我正在努力使用数组帐户,我真的不知道我应该如何处理它,我应该如何初始化它以便正确地 append object accountFromJohn 到列表帐户。
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.最好的里格斯,在此先感谢。
Everything is fine.一切都很好。
The array contains an instance of BankAccount
rather than an arbitrary variable name accountFromJohn
.该数组包含BankAccount
的实例,而不是任意变量名accountFromJohn
。
Prove it by printing通过打印证明它
print(ING.accounts.first?.customer ?? "Accounts is empty")
However it's possible to print accountFromJohn
.但是可以打印accountFromJohn
。 in BankAccount
adopt CustomStringConvertible
and add the property在BankAccount
中采用CustomStringConvertible
并添加属性
var description : String {
return "accountFrom\(customer)"
}
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
然后你可以 append 数据到银行列表,比如yourObject.append(ING)
,如果你想更改账户的值,你可以通过yourObject[desiredElement].accounts.append(accountsData)
来完成,如果你需要检索值yourObject[desiredElement].accounts
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.