- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
像许多人一样,我正在学习 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/
目录 实践1 —— 从字符串中移除星号 栈和数组存储数据的方式一样,它们都只是元素的列表。不同之处在于栈的以下3个限制: 数据只能从栈末插入; 数据只
准备工作 工具:idea+jdk8 技术要求:java基础语法 编码环节 首先,我们得先确定下来,用什么数据来模拟栈的操作。由于是一个一个的元素放入栈里面,我们可以考虑用数组来实现。
0. 学习目标 栈和队列是在程序设计中常见的数据类型,从数据结构的角度来讲,栈和队列也是线性表,是操作受限的线性表,它们的基本操作是线性表操作的子集,但从数据类型的角度来讲,它们与线性表又有着巨大的不
在可以使用递归(在堆栈中存储状态)和对象创建(在堆中创建新对象)的场景中。 问题 在对象创建和递归之间进行选择时应考虑哪些参数? 我的研究得出以下结论(需要验证这一点) 当可用内存较少时:使用递归 可
下面是我编写的用于检查内存对齐的示例程序。 Pavan@Pavan-pc:~/working_dir/pavan/C$ cat mem3.c #include #include
Instapaper 和 Twitterrific 等应用启动的 View 不是其导航堆栈的 Root View 。我们知道这一点,因为初始 View 已经有一个后退按钮。 Instapaper 推出
有没有办法在调试或正常运行期间的某个时刻可视化 Activity 堆栈? 最佳答案 您可以通过 Activity 管理器获取一些有用的信息。 ActivityManager manag
我想编写一个应用层协议(protocol),在发送 GET 请求时使用 TCP 返回特定的 ASCII 文本。我读了第一HTTP specification和 the SMTP specificati
1、堆和栈的速度性能分析 堆和栈是jvm内存模型中的2个重要组成部分,自己很早以前也总结过堆和栈的区别,基本都是从存储内
一: 概念 栈,同样是一种特殊的线性表,是一种last in first out(lifo)的形式,现实中有很多这样的例子,
java中stack类继承于vector,其特性为后进先出(lastinfirstout). 入栈和出栈实例图: 实例图的java代码实例: ?
1、单链表 1、在我们数据结构中,单链表非常重要。它里面的数据元素是以结点为单位,每个结点是由数据元素的数据和下一个结点的地址组成,在java集合框架里面 LinkedList、Ha
本文实例讲述了Python编程实现双链表,栈,队列及二叉树的方法。分享给大家供大家参考,具体如下: 1.双链表 ?
我一遍又一遍地阅读定义,但我仍然不明白ARM中的SP和LR是什么?我了解PC(它显示下一条指令的地址),SP和LR可能类似,但我只是不明白它是什么。你能帮我一下吗? 编辑:如果你能用例子来解释它,那就
我必须使用索引 0 作为堆栈的顶部,并且在实现此操作时遇到问题。我得到了所有 null,但输出 100、200 和 300 是我得到的唯一数字。我忽略的实现有什么问题吗? push 方法应该实现 Ar
我正在用 Java 解决汉诺塔问题。我选择使用 Stacks 作为钉子,除了 move 方法之外,一切都正常。我有规范和 JUnit 测试类,目前通过了 7 项测试中的 6 项,但在移动测试中失败了。
这个问题在这里已经有了答案: 关闭 11 年前。 Possible Duplicate: Does this type of memory get allocated on the heap or
首先,抱歉我的英语不好。我将尝试解释我的问题: 我有一个 RootViewController(基于导航的项目)。因此,它显示了表格 View ,当用户选择表格的一行 (didSelectRowAtI
我有一个看起来像这样的类 class A { int b; void B() { int c; } } int main() { A asdf;
我从一本书中复制了这段代码。在每条评论中,我都放了一个数字,然后问你与该数字评论的代码行相关的问题(1、2、3、4)。希望没事。 1) ESP 指向这些缓冲区值。为什么我们在这里看不到“A”的 0x4
我是一名优秀的程序员,十分优秀!