【问题标题】:Incorrect implementation of String.removeSubrange?String.removeSubrange 的错误实现?
【发布时间】:2018-12-08 20:59:46
【问题描述】:

我在 String.removeSubrange 函数中遇到了一个奇怪的行为。 文档是这样说的:

删除给定范围内的字符。

参数

bounds 要删除的元素的范围。上限和下限 of bounds 必须是字符串的有效索引并且不等于 字符串的结束索引。

bounds 要删除的元素的范围。上限和下限 of bounds 必须是字符串的有效索引。

文档已经说明范围不能包括字符串的endIndex,但我认为应该改变。

让我们看一个例子。 我有一个字符串“12345”,我想删除前三个字符,这将导致“45”。 代码如下:

// Remove the characters 123
var str = "12345"
let endRemoveIndex = str.index(str.startIndex, offsetBy: 2)
str.removeSubrange(str.startIndex...endRemoveIndex)

到目前为止一切顺利,我只是创建了一个从 startIndex 到 startIndex 的封闭范围,提前了 2。

假设我想删除字符“345”,我希望以下代码可以工作:

str = "12345"
let startRemoveIndex = endRemoveIndex
str.removeSubrange(startRemoveIndex...str.endIndex)

但是,正如文档已经提到的那样,这不起作用。 这会导致 fatalError 说

无法超过 endIndex

删除最后三个字符的代码如下:

// Remove the characters 345
str = "12345"
let startRemoveIndex = endRemoveIndex
str.removeSubrange(startRemoveIndex..<str.endIndex)

我认为这在语法上是不正确的,因为半范围运算符意味着不包括最大值,但在这种情况下它是。

你怎么看?

【问题讨论】:

  • str.endIndex 是字符串的末尾索引——str.endIndex 之前的索引是字符串最后一个字符的索引。
  • 来自documentation:字符串的“结束”位置,即比最后一个有效下标参数大一的位置。
  • @Hamish 好吧,现在说得通了,我还没有阅读有关 String.endIndex 的文档。谢谢!

标签: ios swift string macos


【解决方案1】:

Hamish 指出 String.endIndex 是一个“结束”位置,即比最后一个有效下标参数大一的位置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-02
    • 2016-08-05
    相关资源
    最近更新 更多