簡體   English   中英

在 Class - Swift 中初始化數組

[英]Initialize Array in Class - Swift

我正在努力使用數組帳戶,我真的不知道我應該如何處理它,我應該如何初始化它以便正確地 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]

最好的里格斯,在此先感謝。

一切都很好。

該數組包含BankAccount的實例,而不是任意變量名accountFromJohn

通過打印證明它

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

但是可以打印accountFromJohn BankAccount中采用CustomStringConvertible並添加屬性

var description : String {
    return "accountFrom\(customer)"
}

作為一種方法,您可以在初始化對象時為帳戶分配值。

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

然后,您可以正確處理這些對象。

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

然后你可以 append 數據到銀行列表,比如yourObject.append(ING) ,如果你想更改賬戶的值,你可以通過yourObject[desiredElement].accounts.append(accountsData)來完成,如果你需要檢索值yourObject[desiredElement].accounts

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM