[我得到一个: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)
}
}
}
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
追加仅允许您一次添加一个对象,而+ =允许您将对象数组与另一个对象组合在一起。当您在setter上调用append时,您试图添加一个书本对象数组,或[Book]而不是一个书本对象。
[如果您想在附加后添加[newBook],则可以使用:of1- onShelfBooks。append((contentsOf:newBook)“ contentOf”是Sequence的类型。否则使用:2- onShelfBooks + = newBook