不能增加超过 endIndex [英] Cannot increment beyond endIndex

查看:26
本文介绍了不能增加超过 endIndex的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm looking for the "Swift 3" way of handling an error where I try to increment the position of a string to an out of bounds index. I have an extension that looks like the following:

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

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

In implementation code, I have a loop which periodically takes chunks of a string and moves the index further in the string. My problem is I'm not sure what the Swift 3 way is of handling "End of String, do not proceed if we've reached the end"

实现代码就像这样:

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

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

if pos + 1 is the end of the string, it shouldn't error out, but should instead just exit/return from my loop. What's the best way of doing that?

推荐答案

你可以这样写

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"

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

这样的事情会产生致命错误.

What does happen if you pass the wrong param?

Something like this will generate a fatal error.

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

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

You can make you code safer adding a guard statement like this

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)
    }
}

这篇关于不能增加超过 endIndex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆