'subscript' is unavailable: cannot subscript String with a CountableClosedRange, see the documentation comment for discussion

前端 未结 8 830
谎友^
谎友^ 2021-01-31 13:57

In Swift 4, I\'m getting this error when I try to take a Substring of a String using subscript syntax.

\'subscript\' is unavaila

相关标签:
8条回答
  • 2021-01-31 14:54

    Based on p-sun's answer

    Swift 4

    extension StringProtocol {
        subscript(bounds: CountableClosedRange<Int>) -> SubSequence {
            let start = index(startIndex, offsetBy: bounds.lowerBound)
            let end = index(start, offsetBy: bounds.count)
            return self[start..<end]
        }
    
        subscript(bounds: CountableRange<Int>) -> SubSequence {
            let start = index(startIndex, offsetBy: bounds.lowerBound)
            let end = index(start, offsetBy: bounds.count)
            return self[start..<end]
        }
    }
    

    Notable changes:

    • Now an extension of StringProtocol. This allows adopters such as Substring to also gain these subscripts.
    • End indices are offset from the start index of the bounds rather than the start of the string. This prevents traversing from the start of the String twice. The index method is O(n) where n is the offset from i.
    0 讨论(0)
  • 2021-01-31 14:55

    Your question (and self-answer) has 2 problems:

    Subscripting a string with Int has never been available in Swift's Standard Library. This code has been invalid for as long as Swift exists:

    let mySubstring: Substring = myString[1..<3]
    

    The new String.Index(encodedOffset: ) returns an index in UTF-16 (16-bit) encoding. Swift's string uses Extended Grapheme Cluster, which can take between 8 and 64 bits to store a character. Emojis make for very good demonstration:

    let myString = "                                                                    
    0 讨论(0)
提交回复
热议问题