【问题标题】:Swift 4: 'subscript' is unavailable errorSwift 4:“下标”不可用错误
【发布时间】:2017-11-09 02:59:46
【问题描述】:

我正在使用尚未完全更新到 Swift 4 的 MapBox 导航框架。我有一个无法完全解决的“下标”错误。这是代码。我真的很感激任何帮助。谢谢。

private func extractNextChunk(_ encodedString: inout String.UnicodeScalarView) throws -> String {
    var currentIndex = encodedString.startIndex

    while currentIndex != encodedString.endIndex {
        let currentCharacterValue = Int32(encodedString[currentIndex].value)
        if isSeparator(currentCharacterValue) {
            let extractedScalars = encodedString[encodedString.startIndex...currentIndex]
            encodedString = encodedString[encodedString.index(after: currentIndex)..<encodedString.endIndex]

            return String(extractedScalars)
        }

        currentIndex = encodedString.index(after: currentIndex)
    }

    throw PolylineError.chunkExtractingError
}

【问题讨论】:

    标签: swift mapbox swift4 subscript swift-subscript


    【解决方案1】:

    错误信息具有误导性。真正的问题是下标 带有范围的String.UnicodeScalarView 返回String.UnicodeScalarView.SubSequence,因此您不能将其分配回 encodedString.

    一种解决方案是创建一个String.UnicodeScalarView 从子序列:

    encodedString = String.UnicodeScalarView(encodedString[encodedString.index(after: currentIndex)...])
    

    或者(也许更简单)反过来, 改为删除encodedString 的初始部分:

    encodedString.removeSubrange(...currentIndex)
    

    在任何一种情况下,您都可以使用“单边范围”,比较 SE-0172

    【讨论】:

    • 感谢您的回答。我会做一个测试。您能否将其添加到我上面粘贴的实际代码中?这将是一个巨大的帮助,因为我不是 100% 确定你的答案。我确定这是解决方案
    • @ChelsMcKay:只需替换导致编译器错误的encodedString = ... 行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-22
    • 1970-01-01
    • 2023-04-06
    • 2018-08-02
    相关资源
    最近更新 更多