我正在寻找“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/