我无法弄清楚如何声明"如果可选"在Swift上使用类的堆栈上。 这是我使用类在Swift上堆栈的通用代码(本书使用struct但我被告知要使用类)。
class Stack {
var items = [String]()
func push(item: String) {
items.append(item)
}
func pop() -> String {
return items.removeLast()
}
func length() -> Int {
return items.count
}
}
我创建了一个Stack的实例:
var stringStack = Stack()
...
stringStack.pop()
当我弹出时,堆栈会删除最后一项。我想这样做,如果我执行pop(0),堆栈将删除第一项,但如果我只是执行pop(),堆栈只删除最后一项。我想用if ...返回items.removeAtIndex(0)或items.removeLast()来创建一个可选值。我似乎无法正确使用语法而且我一直都会遇到错误。我能够使它成为pop(0)删除堆栈中的第一项,但如果我执行pop()我会收到错误。如果有人可以向我展示代码来做我想做的事情,那将非常有帮助。我在编码方面仍然非常非常新,我不太了解。抱歉尴尬!
答案 0 :(得分:1)
您正在寻找带有默认值的可选参数。这样,您就可以调用pop()
删除堆栈中的最后一项,或pop(index)
删除特定项目。
使用参数调用pop
表示可选index
具有值,因此使用第一个返回值。在没有参数的情况下调用会使index
保持默认值,因此if语句会失败,而是删除最后一项。
func pop(_ index: Int? = nil) -> String {
if let i = index {
return items.removeAtIndex(i)
}
return items.removeLast()
}
// ...
stack.pop(0)
stack.pop()
答案 1 :(得分:0)
您必须重载pop
函数,即创建具有不同签名的2个版本。另外我建议返回一个可选项,因为如果数组为空,或者如果要求它弹出一个不存在的项,它将生成一个运行时异常。这是修改后的版本:
class Stack {
var items = [String]()
func push(item: String) {
items.append(item)
}
func pop() -> String? {
return length() > 0 ? items.removeLast() : nil
}
func pop(index: Int) -> String? {
return index < length() ? items.removeAtIndex(index) : nil
}
func length() -> Int {
return items.count
}
}
Swift与Objective-C相比的一个(最受赞赏的特性)新功能是泛型,那么为什么不在像堆栈这样的容器类中使用它呢?这是:
class Stack<T> {
var items = [T]()
func push(item: T) {
items.append(item)
}
func pop() -> T? {
return length() > 0 ? items.removeLast() : nil
}
func pop(index: Int) -> T? {
return index < length() ? items.removeAtIndex(index) : nil
}
func length() -> Int {
return items.count
}
}
通过这种方式,您可以重复使用它来存储任何类型的数据,而不是将其仅限于字符串