// Substring
func substring(_ start: Int, end: Int) -> String {
return self.substring(with: Range(self.characters.index(self.startIndex, offsetBy: start) ..< self.characters.index(self.startIndex, offsetBy: end)))
}
将 Xcode 更新到 10.0 后,在该 return 语句中出现以下错误。让我知道如何根据最新的 swift 版本显示返回语句。
Cannot invoke initializer for type 'Range<_>' with an argument list of type '(Range)'
最佳答案
使用 Xcode 10,您可以在 Swift 3、Swift 4 和 Swift 4.2 版本之间进行选择。
当您谈论最新的 Swift 版本时,我假设您指的是 Swift 4.2。请记住,自 Swift 4 以来,substring(with:)
函数已被弃用,因此您可以使用字符串切片:
extension String {
func substring(_ start: Int, end: Int) -> String {
let startIndex = self.index(self.startIndex, offsetBy: start)
let endIndex = self.index(self.startIndex, offsetBy: end)
return String(self[startIndex...endIndex])
}
}
关于swift - 使用范围的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53130079/