为什么我不能在Swift中使用数组的append()?

问题描述 投票:0回答:3

[我得到一个:Cannot invoke 'append' with an argument list of type '([Book])',可以找到是否使用+=,但我不明白为什么append()不起作用。

struct Book
{
    var title:String
    var pageCount:Int
}

class Library
{
    var onShelfBooks:[Book] = []
    var onLoanBooks:[Book] = []
    var books:[Book]
    {
        get
        {
            return onShelfBooks + onLoanBooks
        }

        set(newBook)
        {
            onShelfBooks.append(newBook)
        }
    }
}
arrays swift struct append
3个回答
3
投票
struct Book
{
    var title:String
    var pageCount:Int
}

class Library
{
    var onShelfBooks:[Book] = []
    var onLoanBooks:[Book] = []
    var books:[Book]
    {
        get
        {
            return onShelfBooks + onLoanBooks
        }

        set(newBook)
        {
            onShelfBooks.append(newBook[0])
        }
    }
}

var myLibrary = Library()

var newBook = Book(title: "Swift Development with Cocoa", pageCount: 453)

myLibrary.books = [newBook]

myLibrary.books

2
投票

追加仅允许您一次添加一个对象,而+ =允许您将对象数组与另一个对象组合在一起。当您在setter上调用append时,您试图添加一个书本对象数组,或[Book]而不是一个书本对象。


0
投票

[如果您想在附加后添加[newBook],则可以使用:of1- onShelfBooks。append((contentsOf:newBook)“ contentOf”是Sequence的类型。否则使用:2- onShelfBooks + = newBook

© www.soinside.com 2019 - 2024. All rights reserved.