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

前端 未结 8 828
谎友^
谎友^ 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) -> SubSequence {
            let start = index(startIndex, offsetBy: bounds.lowerBound)
            let end = index(start, offsetBy: bounds.count)
            return self[start..) -> SubSequence {
            let start = index(startIndex, offsetBy: bounds.lowerBound)
            let end = index(start, offsetBy: bounds.count)
            return self[start..

    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.

提交回复
热议问题