我收到了: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)
}
}
}
答案 0 :(得分: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
答案 1 :(得分:2)
追加仅允许您一次添加一个对象,而+ =允许您将对象数组与另一个对象组合。当你在setter上调用append时,你试图添加一个book对象数组,或者[Book]而不是只有一个book对象。
答案 2 :(得分:0)
如果您想在附加[newBook]的同时添加,可以使用:of
在书架上 1-。追加( contents :newBook)
“ contentOf”是序列的类型。
其他用途:
2- onShelfBooks + = newBook