Ios Swift类函数在for in循环后返回空
我试图在Swift中构建一个简单的图书馆书架图书模型,但遇到了一个奇怪的问题。在以下库类中,my func total book count每次都返回0。我知道这可能是我忽略的一些简单的事情,但任何帮助都会很棒。这是我的图书馆课:Ios Swift类函数在for in循环后返回空,ios,arrays,swift,for-in-loop,Ios,Arrays,Swift,For In Loop,我试图在Swift中构建一个简单的图书馆书架图书模型,但遇到了一个奇怪的问题。在以下库类中,my func total book count每次都返回0。我知道这可能是我忽略的一些简单的事情,但任何帮助都会很棒。这是我的图书馆课: class Library { var allShelves:[Shelf]=[] var allBooksCount = 0 var description: String{ return "This Library has \(allShelves.c
class Library
{
var allShelves:[Shelf]=[]
var allBooksCount = 0
var description: String{
return "This Library has \(allShelves.count) Shelves with \(allBooksCount) books"
}
func addNewShelf(newShelf: Shelf){
var newShelf = Shelf()
self.allShelves.append(newShelf)
println("There are \(allShelves.count) SHELVES in this library")
}
func totalBookCount() -> Int{
for currentShelf in allShelves{
allBooksCount = currentShelf.numberOfBooks
}
return allBooksCount
}
}
这是我的书架课:
class Shelf
{
var allBooksOnShelf:[Book] = []
var numberOfBooks = 0
init(){
self.allBooksOnShelf = []
}
var description: String{
return "This Shelf has \(allBooksOnShelf.count) Books"
}
func addNewBook(newBookToAddToShelf: Book){
let newBook = Book(bookName: newBookToAddToShelf.bookName)
self.allBooksOnShelf += [newBookToAddToShelf]
numberOfBooks = allBooksOnShelf.count
println("new book called \(newBook.bookName)")
}
}
以下是我的测试:
let newLibrary = Library()
//println(newLibrary.description)
let libraryShelf1 = Shelf()
newLibrary.addNewShelf(libraryShelf1)
let libraryShelf2 = Shelf()
newLibrary.addNewShelf(libraryShelf2)
libraryShelf1.addNewBook(Book(bookName: "Game Of Thrones"))
libraryShelf1.addNewBook(Book(bookName: "Hunger Games"))
libraryShelf1.addNewBook(Book(bookName: "Return of the Jedi"))
println("this Shelf has \(libraryShelf1.allBooksOnShelf.count) books")
newLibrary.totalBookCount()
println(newLibrary.description)
newLibrary.totalBookCount()始终返回0。我看到两个错误:
错误1
func addNewShelf(newShelf: Shelf){
var newShelf = Shelf()
^^^^^^^^^^^^
self.allShelves.append(newShelf)
println("There are \(allShelves.count) SHELVES in this library")
}
在这里,您将newShelf
参数重新定义为局部变量,从而丢失传入的内容。正确的实施方式是:
func addNewShelf(newShelf: Shelf){
self.allShelves.append(newShelf)
println("There are \(allShelves.count) SHELVES in this library")
}
错误2
在这里:
在每次迭代中,您都会重新初始化allBooksCount
属性,因此func最终返回的是循环中最后一个工具架的计数。您应该添加(使用+=
运算符)-此外,在开始时重置计数器也是一个好主意(否则,如果多次调用该函数,则会得到错误的结果):
使用调试器跟踪并观察变量值。哇!非常感谢!我知道这是一个小东西,它工作得很好,谢谢!!很高兴它成功了:)别忘了把答案标记为解决方案
func totalBookCount() -> Int{
for currentShelf in allShelves{
allBooksCount = currentShelf.numberOfBooks
}
return allBooksCount
}
func totalBookCount() -> Int{
self.allBooksCount = 0
for currentShelf in allShelves{
allBooksCount += currentShelf.numberOfBooks
}
return allBooksCount
}