如何初始化包含另一个结构数组的结构?
我想创建一个发票条目,其中所有属性和项都有一个invoiceitem数组。
另外,当发票仍然是汇票时,项目可以为空。
从带有发票数据和项目的服务器读取json响应可以正常工作。
在viewcontroller的save操作中,我有:

var invoice: Invoice?
var client: Client?
var invoiceItems : [InvoiceItem] = [InvoiceItem]()

@IBAction func saveInvoice(_ sender: Any) {

...

invoice = Invoice(invoice_id: invoice?.invoice_id, client_id: client_id, tax: 0.00, date_issue: dateIssue, due_date: dueDate,
amount_paid: 0.00,
date_transaction: "0000-00-00",
voided: 0,
note: "",
invoice_number: "",
status: "",
items: invoiceItems
)

override func viewDidLoad() {

...
 invoiceItems = (invoice?.items)!
...
}

我收到此错误:无法将类型为“[Invoiceitem]”的值转换为预期的参数类型“Invoiceitem”,联机:items:Invoiceitems
struct InvoiceItem: Codable {
    var invoice_detail_id: Int!
    let description: String!
    let unit_price: Decimal!
    let quantity: Decimal!

    init(invoice_detail_id: Int! = nil, description: String, unit_price: Decimal, quantity: Decimal) {
        self.invoice_detail_id = invoice_detail_id
        self.description = description
        self.unit_price = unit_price
        self.quantity = quantity
    }
}

struct Invoice: Codable {
    var invoice_id: Int!
    let client_id: Int!
    let tax: Decimal!
    let date_issue: String!
    let due_date: String!
    let amount_paid: Decimal!
    let date_transaction: String!
    let voided: Int!
    let note: String!
    let invoice_number: String!
    let status: String!
    let items: [InvoiceItem]!

    init(invoice_id: Int! = nil, client_id: Int! = nil,tax: Decimal, date_issue: String, due_date: String, amount_paid: Decimal, date_transaction: String, voided: Int, note: String, invoice_number: String, status: String, items: InvoiceItem) {
        self.invoice_id = invoice_id
        self.client_id = client_id
        self.tax = tax
        self.date_issue = date_issue
        self.due_date = due_date
        self.amount_paid = amount_paid
        self.date_transaction = date_transaction
        self.voided = voided
        self.note = note
        self.invoice_number = invoice_number
        self.status = status
        self.items = [items]
    }


}

最佳答案

您的invoice init有items: InvoiceItem作为参数。项的类型是InvoiceItem,而不是InvoiceItem的数组。
将类型更改为InvoiceItem数组。
编辑:
在您的发票init中,您有:

self.items = [items]

您试图将InvoiceItem数组传入定义为items: InvoiceItem的参数。
显然这是行不通的,所以我告诉过你把参数类型改成InvoiceItem数组。
现在已经有了,您正在数组中包装InvoiceItem数组。所以你有一个数组InvoiceItem
将该代码行更改为:
self.items = items

关于arrays - Swift-将结构体数组传递给另一个结构体的init,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49034286/

10-11 14:11