gpt4 book ai didi

swift - 简单的栈例子,栈为空如何返回?

转载 作者:搜寻专家 更新时间:2023-11-01 06:49:18 25 4
gpt4 key购买 nike

像许多人一样,我正在学习 Apple 的新 Swift 语言,通过教程我遇到了一个创建通用堆栈的示例。这是该示例中的 pop 函数 ...

mutating func pop() -> T {
return elements.removeLast()
}

我决定扩展此实现,使其在元素数组为空时不弹出,但作为 Swift 的新手,我不确定如果堆栈为空则返回什么。

mutating func pop() -> T {
if !elements.isEmpty {
return elements.removeLast()
} else {
// return nothing?
}

我的问题是在 Swift 中执行此操作的最佳方法是什么

最佳答案

这正是可选类型的用途。可选变量就像常规变量,除了它们有一个特殊情况,“没有赋值”,所以不是返回类型“T”,而是返回类型“可选 T”:

mutating func pop() -> T? {
if !elements.isEmpty {
return elements.removeLast() // return the last item on the stack
} else {
return nil // indicate there was nothing on the stack
}
}

当然,在使用此函数时,您必须检查是否获得了实际值。您可以使用“if”语句或“if let”结构来做到这一点。如果您在名为 optionalItem 的 var 中有一个可选项,则可以使用类似 if optionalItem { ... } 的内容。只有当 optionalItem 有值时,才会执行 if block 中的代码。

“if let”构造更进一步,为您从可选项中检索项目。做这样的事情:

if let item = myStack.pop() { // this implicitly unwraps the optional if present
// Do something. "item" is of type T, not T?
else {
// Nothing was on the stack. "item" is not defined
}

关于swift - 简单的栈例子,栈为空如何返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24222141/

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