【问题标题】:How to use String subscript in Swift 4 [duplicate]如何在 Swift 4 中使用字符串下标 [重复]
【发布时间】:2017-09-02 07:17:34
【问题描述】:

我正在尝试将 Swift 3 代码转换为 Swift 4。但此错误显示:

"substring(from:)' 已弃用:请使用字符串切片下标 使用 'partial range from' 运算符。”

我的代码是:

extension String {

    func substring(_ from: Int) -> String {
        return self.substring(from: self.characters.index(self.startIndex, offsetBy: from))
    }

}

【问题讨论】:

标签: ios swift


【解决方案1】:

你应该有:

extension String {

    func substring(_ from: Int) -> String {
        let start = index(startIndex, offsetBy: from)
        return String(self[start ..< endIndex])
    }
}

在 swift 中,您可以使用切片获取子字符串 - 如下结构:string[startIndex ..&lt; endIndex]。字符串索引是 swift 中的一种特殊类型,因此您不能使用简单的整数 - 您必须获取正确的索引,例如调用 index(_,offsetBy:) 或使用预定义的 startIndexendIndex

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-07
    • 2016-08-30
    相关资源
    最近更新 更多