gpt4 book ai didi

ios - Swift 类函数在 for-in 循环后返回空

转载 作者:行者123 更新时间:2023-11-29 02:30:46 25 4
gpt4 key购买 nike

我试图在 Swift 中构建一个简单的图书馆-书架-图书模型,但我遇到了一个奇怪的问题。在以下图书馆类(class)中,我的 func 总书数每次都返回 0。我知道这可能是我忽略的一些简单的事情,但任何帮助都会很棒。这是我的图书馆类(class):

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
}


}

这是我的 Shelf 类:

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。

最佳答案

我看到 2 个错误:

错误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

这里:

func totalBookCount() -> Int{
for currentShelf in allShelves{
allBooksCount = currentShelf.numberOfBooks
}
return allBooksCount
}

在每次迭代中,您都会重新初始化 allBooksCount 属性,因此最终 func 返回的是循环中最后一个书架的计数。您应该改为添加(使用 += 运算符)- 此外,在开始时重置计数器也是一个好主意(否则,如果您多次调用该函数,您会得到不正确的结果):

func totalBookCount() -> Int{
self.allBooksCount = 0
for currentShelf in allShelves{
allBooksCount += currentShelf.numberOfBooks
}
return allBooksCount
}

关于ios - Swift 类函数在 for-in 循环后返回空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26914569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com