swift - 使用范围的子字符串

标签 swift range substring

// 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/

相关文章:

ios - 响应 child 和 parent 的触摸事件

ios - 如何使用 youtube-ios-player-helper 库在 iOS 中更改 youtube 视频的音量

vba - 如何在 vba 中为一组特定字符设置 Word 的范围?

mysql过滤json数据取值范围

regex - Powershell 使用 Regex 在字符串中查找字符串

ios - 导航栏中的中心图像

ios - AppDelegate:在解包可选值时意外发现 nil

跨浏览器范围的 Javascript 插件

python - Pandas 在另一个系列的一个系列中找到 super 字符串

从多个列名称中删除第一个字符