swift - 不能超过 endIndex

标签 swift swift3

我正在寻找“Swift 3”处理错误的方法,我尝试将字符串的位置增加到越界索引。我有一个如下所示的扩展:

extension String {
  func substring(from: Int) -> String {
        let fromIndex = index(from: from)
        return substring(from: fromIndex)
  }
}

在实现代码中,我有一个循环,它定期获取字符串 block 并将索引进一步移动到字符串中。我的问题是我不确定 Swift 3 处理“字符串结尾,如果我们已经到达结尾就不要继续”的方式是什么

实现代码是这样简单的:

myStr = myStr.substring(from: pos + 1)

如果 pos + 1 是字符串的结尾,它不应该出错,而应该只是退出/返回我的循环。这样做的最佳方式是什么?

最佳答案

你可以这样写

extension String {
    func substring(from offset: Int) -> String {
        let fromIndex = index(self.startIndex, offsetBy: offset)
        return substring(from: fromIndex)
    }
}

例子

"Hello world".substring(from: 0) // "Hello world"
"Hello world".substring(from: 1) // "ello world"
"Hello world".substring(from: 2) // "llo world"

如果你传递了错误的参数会发生什么?

这样的事情会产生 fatal error 。

"Hello world".substring(from: 12)
fatal error: cannot increment beyond endIndex

你可以让你的代码更安全添加这样的保护语句

extension String {
    func substring(from: Int) -> String? {
        guard from < self.characters.count else { return nil }
        let fromIndex = index(self.startIndex, offsetBy: from)
        return substring(from: fromIndex)
    }
}

关于swift - 不能超过 endIndex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41468014/

相关文章:

Swift 的内存管理

swift3 - 在 Swift 3 下使用 startDeviceMotionUpdates

ios - XLPagerTabStrip:标题标签未显示在寻呼机选项卡上

ios - Swift 中从 UIScrollView 到其他 View 的 Segue

ios - 如何在 Xcode playground 中使用自动布局约束显示 View ?

c - string.withCString 和 UnsafeMutablePointer(变异 : cstring) wrapped into a function

ios - Swift异步加载报错

swift - `UnsafePointer` 机制能否显示数据缓冲区中的向量数组以供在 SceneKit 中使用?

ios - 在复杂的 View 层次结构中查找 CGRect

swift - 更改所有 SKTextures 的 SKTextureFilteringMode