- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这些评论有道理吗?试图找出为什么它删除了我的反向给定字符串的字符,而不是本例中的常规给定字符串。
import Foundation
extension String {
func reverseWords() -> String {
var result = ""
let words = self.componentsSeparatedByString(" ")
for thisWord in words.reverse() {
result += thisWord + " "
}
print("..\(result)..")
// Result is the words array ( contains self ) reversed with seperator " "
print("..\(self)..")
result.removeAtIndex(self.endIndex.predecessor())
// So here i am checking self within result?, and am removing the last index
// of my currently reversed given string inside result?
// I do result in my intended last space removal with result.endIndex but i'm
// wondering what happens in this case with the self.endIndex :)
return result
}
}
var str = "This string contains a few elements"
str.reverseWords()
最佳答案
self
仍然引用原始的未反转的 String
。
正确的代码是:
result.removeAtIndex(result.endIndex.predecessor())
您永远不应该将String
索引用于另一个字符串。如果您要对 result
建立索引,则不应使用 self
中的索引。
对于一个简单的字符串,你看起来不会有什么不同,但如果你开始添加多字节字符,例如表情符号,您的应用程序可能会崩溃。
例如,使用 result += thisWord + "😀"
将导致:
elements😀few😀a😀contains😀string�This😀
与self.endIndex
和
elements😀few😀a😀contains😀string😀This
与result.endIndex
。
endIndex
是超过String
末尾的索引。它的工作原理与数组的 count
相同。数组中的 count
不代表最后一个元素,count - 1
代表最后一个元素。
如果您的目标是更改原始String
,则必须将该方法声明为mutating
并分配给self
,例如:
mutating func reverseWords() {
var result = ""
let words = self.componentsSeparatedByString(" ")
for thisWord in words.reverse() {
result += thisWord + " "
}
self = result
self.removeAtIndex(self.endIndex.predecessor())
}
尽管这在函数式编程中相当罕见。
关于Swift - endIndex.predecessor(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38059489/
这些评论有道理吗?试图找出为什么它删除了我的反向给定字符串的字符,而不是本例中的常规给定字符串。 import Foundation extension String { func reverse
我正在尝试实现一个类 Node 表示有向图中的一个节点,特别是有一组后继者和前任者。我希望 Node.predecessors 和 Node.predecessors 表现得像集合,特别是我想遍历它们
我在 div 上使用 :after 来添加叠加背景(在我的例子中,我不能将它作为第二个添加到原始 div) 我试图强制它占据其“前任”div 的整个宽度和高度,尝试将宽度和高度设置为 100% 以及继
我正在努力定义 REST Api: 我正在为事务系统建模 Api:现在我已经为事务资源定义了一些端点。我的端点是: POST /transactions GET /transactions/{id}
我正在尝试可视化 Floyd-Warshall 算法。问题是当它找到路径长度时,不需要有前辈在找到的时候准备好构建这条路径,所以我不能实际显示路径,虽然距离已经知道了。让我解释一下维基百科的例子: 这
我需要构建查询,该查询返回具有超过 2 级深度的网络拓扑的结果。例如,我不会得到下一个结果: 但如果我构建“工作项和直接链接”查询,我只会得到 1 级深度,如果我构建“工作项树”,我只能选择父/子树类
我正在尝试实现 D* Lite和 LPA*算法(均由 Sven Koenig 提出),我很难理解每个节点包含的前驱和后继列表的概念。我尝试在各种来源寻找答案,但找不到确定的答案。 谁能帮我解决一下?
我有一个循环,它创建父行和可变数量的子行。我想用前一个子行号更新子行的前一个字段(当添加多个子行时)。我在将 2 个必需参数添加到“cell.object_value”对象(object_type 和
我用NestedScrollView构建的滚动页面有问题,开始滚动有一定概率报错,这里看报错: I/flutter ( 6574): ══╡ EXCEPTION CAUGHT BY GESTURE L
我无法向链添加新 block ,因为锯齿 validator 默认正在报告:[2019-01-25 18:18:54.029 警告 block_validator] 区 block 7f3...370
我是一名优秀的程序员,十分优秀!